- 安装requests,beautifulsoup要安装beautifulsoup4,而不是BeautifulSoup。安装方法可以使用pip install requests等,还可以使用settings安装参见:https://jingyan.baidu.com/article/8cdccae92b641a315413cd81.html
- 把列表中的首字母大写,其他变成小写。
def ucfirst(list): for x in list: word = x.title() print(word) ucfirst(['i', 'love', 'You','NICE'])
- http://c.biancheng.net/view/2745.html
- 安装twisted:https://blog.csdn.net/wsgjcxy13/article/details/88218931
- 虚拟环境:settings -》project interpreter -》下拉框选择showall -》选择环境的路径(如果是新加环境则点击 + 添加) -》安装库什么的一定要弄清楚是哪个虚拟环境。
- pip list 可以查看当前虚拟环境安装了那些库啊,包啊之类。
- pip --version 可以查看当前虚拟环境路径。
- 缺少win32api安装的时候报错:No matching distribution found for win32api -------》》改成 pip install pypiwin32
- selenium:使用JavaScript编写
- selenium通过各浏览器对应的driver来控制浏览器,比如chromedriver来控制Chrome浏览器。这样我们就可以写Python代码来间接操控浏览器。流程就是Python-》selenium-》Chromedriver-》Chrome浏览器。
- selenium 文档: 搜索 selenium Python api
- 下载Chromedriver 地址:https://chromedriver.storage.googleapis.com/index.html? 在下载之前需要看Chrome浏览器的版本,下载对应的版本。一切部署好之后,写代码
from selenium import webdriver browser = webdriver.Chrome(executable_path="D:/Python/xingzuo_spider/zuixingzuo_spider/chromedriver.exe") browser.get("https://baike.baidu.com/vbaike") print(browser.page_source) #打开一个Chrome浏览器
模拟登陆:
from selenium import webdriver browser = webdriver.Chrome(executable_path="D:/Python/xingzuo_spider/zuixingzuo_spider/chromedriver.exe") browser.get("https://baike.baidu.com/vbaike") print(browser.page_source) # import time # time.sleep(10) #有的时候,比如微博模拟登录,他会在页面没有完全加载出来的时候,就执行下面的代码,就去找我们设置的css选择器,这个时候可能找不到,所以先让他sleep10秒,确保页面所有内容都加载完毕,这样就肯定能找到input输入框。 # browser.find_element_by_css_selector('input[name="username"]').send_keys("username") #找到input元素,使用send_keys填写内容 #browser.quit() 关闭Chrome浏览器
- if else比较多的时候,会显得代码冗长。在某些情况下,可以使用dict代替if else。for instance:
# 只写if else 代码, 其他忽略 if state == 'start': code = 1 elif state == 'running': code = 2 elif state == 'offline': code = 3 else: code = 4 # 类似这种形式的if else 完全可以使用dict 代替 state_dict = {'start': 1, 'running': 2, 'offline': 3} code = state_dict.get(state, 5)