使用selenium+chrome做爬虫注意事项

1、可以开多进程,但是每个使用独立的webdriver,需要复制多份。(chrome自身的问题,单个webdriver会导致蓝屏?)

 

2、一定要经常存数据!爬虫不可靠,可能会意外中断。

如果使用mysql 或者sql,每条数据存一次,或者每隔几条村一次;如果使用namedtuple,则用pickle定期保存

 

3、chrome常见参数添加:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('start-maximized')
chrome_options.add_argument('enable-automation')
chrome_options.add_argument('--disable-infobars')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-browser-side-navigation')
prefs = { "profile.managed_default_content_settings.images": 2 }
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(driver_path, options=chrome_options) # 设置不加载图片

4、使用隐式等待
driver.implicitly_wait(7)

5、ActionChains进行悬停和动态元素点击

6、一定要进行去重!可以使用标题去重,避免资源浪费

7、小心广告页面,可能和正常页面结构不同,会导致出错

8、使用js往下移动动态加载
js = "window.scrollTo(0,10000);"
driver.execute_script(js)
time.sleep(3)

9、合理的点击下一页。可以先获取最大页数,然后循环点击下一页

10、没当打开新窗口,则切换句柄handles,因为句柄可能还停留在上一个。
如果切换到新的句柄,如果新的窗口tab会显示'跳转...',一定要加等待时间,因为跳转后获取句柄需要等待。如果担心效率降低,可以使用
while True:
try:
all_handles = driver.window_handles
driver.switch_to.window(all_handles[2])
break
except Exception as e:
print(e)
time.sleep(0.2)

11、selenium 关闭窗口一定不要使用driver.close()!!!!!!!!!!!!!!!会出错,应该使用
driver.execute_script('window.close()')
12、有些网站元素加载非常慢,我们可以指定一个缓存目录
options.add_argument(r'--disk-cache-dir=C:\Users\Administrator\AppData\Local\Google\Chrome\User Data')
这个目录的缓存我们可以重复使用
chrome添加代理:options.add_argument('--proxy-server={}'.format('43.248.125.211:16816'))
firefox添加代理:
ip = '43.248.125.211'
port = 16816
print('ip:{},port:{}'.format(ip,port))
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
# # ip及其端口号配置为 http 协议代理
profile.set_preference("network.proxy.http", ip)
profile.set_preference("network.proxy.http_port", port)
profile.set_preference("network.proxy.share_proxy_settings", True)

14、edge 配置 https://docs.microsoft.com/zh-cn/deployedge/edge-learnmore-cmdline-options-proxy-settings
posted @ 2020-07-23 09:54  yjy888  阅读(841)  评论(0编辑  收藏  举报