今天本地调试基于Selenium+PhantomJS的动态爬虫程序顺利结束后,着手部署到服务器上,刚买的热乎的京东云,噼里啪啦一顿安装环境,最后跑的时候报了这么个错误:css
UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead
运用我考了五遍才飘过的六级英语定睛一看,这个意思是说,新版本的Selenium再也不支持PhantomJS了,请使用Chrome或Firefox的无头版原本替代。脑瓜里瞬间响起了这首歌的旋律,简直不能接受,凭什么就把咱们PhantomJS抛弃了(╯‵□′)╯︵┻━┻。java
由于这半年都没有写爬虫的需求,而且最近一直在本地用的老版本Selenium开发,因此一直还PhantomJS的很嗨,却不知脚步已经落后了。查了一下,大概是去年七八月份Chrome和Firefox相继推出了无头浏览器模式。可能就由于这样,PhantomJS独领风骚的局面瞬间丧失,而后逐渐消失在历史的尘埃中吧……小厂出的创新产品,大厂作出相似产品以后,小厂GG,大概也是这么一回事吧……python
虽然很不情愿,可是人不能老是追忆过去的美好,该往前走的时候就要往前走对吧~web
其实Selenium+Headless Firefox没什么好说的,跟Selenium+Friefox的区别就是实例化的时候传个参数而已。chrome
须要注意的点就是:ubuntu
本地要有Firefox,否则报找不到载体 本地要有geckodriver,最好再配置一下环境变量 没了浏览器
各个语言的示例代码均可以在这个连接里找到,这里就搬运一下python的示例代码吧:服务器
from selenium.webdriver import Firefox from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from selenium.webdriver.support import expected_conditions as expected from selenium.webdriver.support.wait import WebDriverWait if __name__ == "__main__": options = Options() options.add_argument('-headless') # 无头参数 driver = Firefox(executable_path='geckodriver', firefox_options=options) # 配了环境变量第一个参数就能够省了,否则传绝对路径 wait = WebDriverWait(driver, timeout=10) driver.get('https://www.google.com') wait.until(expected.visibility_of_element_located((By.NAME, 'q'))).send_keys('headless firefox' + Keys.ENTER) wait.until(expected.visibility_of_element_located((By.CSS_SELECTOR, '#ires a'))).click() print(driver.page_source) driver.quit()
win10和ubuntu下我都测试了没问题,从前实例化一个PhantomJS大约3秒,Headless Firefox的话,7秒左右……其实无伤大雅。less
这里友情提示一下新手小伙伴,别每下载一个网页实例化一个webdriver(Firefox or Chrome)而后就close()掉,实例化webdriver的时间也是时间~推荐将下载器作成单例类或将webdirver作类变量。测试
这个跟上边大同小异,我没试,传送门:
PhantomJS在Selenium中被标记为过期的应对措施 Getting Started with Headless Chrome