关于爬虫的浏览器模拟事件

最近做爬虫碰到一个硬茬,用了腾讯的浏览验证,貌似传参是通过腾讯服务器传过去的,js代码也是非常魔性的加一些骚扰信息,倒腾起来很是老火。于是想到了自动浏览器模拟的方法。
开始时使用的是selenium+phantomJS,但是报了如下警告

~/lib/python3.6/site-packages/selenium/webdriver/phantomjs/webdriver.py:49: UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead
  warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless '

担心版本问题对后期爬虫有影响,于是就老老实实的转过来看headless chrome. 我的电脑是Ubuntu的,通过apt安装了一个chromium-browser (73.0.3683.75-0ubuntu0.16.04.1)。科普一下, chromium和chrome是一个妈生的,只是chrome是稳定版本,chromium是实验版本,道理上chromium版本会更加新一些。
然后对应chromium的版本在chromedriver镜像下载网站上找到73.0.3683.68 这个版本,应该是版本好尽量一样,特别是靠前的大版本号。
比如我的chromium是73这个版本,用74版本的chromdriver就不行。总之版本要尽量对应就好了。

然后之前安装了selenium,下面是我的安装命令:

$ conda install selenium  # conda install -c clinicalgraphics selenium
						# 可以加个-c参数指明使用那个库。我看到clinicalgraphics库的版本比较新,所以选择的clinicalgraphics, 视情况而定。

然后就是加载headless 版本的chromium了。代码如下

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--headless')
# chrome_options.add_argument('--disable-gpu') #我认为gpu不用禁用,万一有的地方可以加速,用上估计要快一些。

driver=webdriver.Chrome(chrome_options=chrome_options)
driver.get('http://www.baidu.com/')
print(driver.page_source)
driver.close() 

好了,记录就做到这里了,接着去捣腾了。

参考
如何在Python环境下安装Selenium+Headless Chrome

猜你喜欢

转载自blog.csdn.net/u012939880/article/details/88795643