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()')