首页 > 技术文章 > Selenium+Headless Firefox

pythonClub 2018-10-02 09:40 原文

背景

今天本地调试基于Selenium+PhantomJS的动态爬虫程序顺利结束后,着手部署到服务器上,刚买的热乎的京东云,噼里啪啦一顿安装环境,最后跑的时候报了这么个错误:

UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead

运用我考了五遍才飘过的六级英语定睛一看,这个意思是说,新版本的Selenium不再支持PhantomJS了,请使用Chrome或Firefox的无头版本来替代。脑瓜里瞬间响起了这首歌的旋律,简直不能接受,凭什么就把我们PhantomJS抛弃了(╯‵□′)╯︵┻━┻。

因为这半年都没有写爬虫的需求,并且最近一直在本地用的老版本Selenium开发,所以一直还PhantomJS的很嗨,殊不知脚步已经落后了。查了一下,大概是去年七八月份Chrome和Firefox相继推出了无头浏览器模式。可能就因为这样,PhantomJS独领风骚的局面瞬间丧失,然后逐渐消失在历史的尘埃中吧……小厂出的创新产品,大厂做出类似产品之后,小厂GG,大概也是这么一回事吧……

Selenium+Headless Firefox

虽然很不情愿,但是人不能总是追忆过去的美好,该往前走的时候就要往前走对吧~

其实Selenium+Headless Firefox没什么好说的,跟Selenium+Friefox的区别就是实例化的时候传个参数而已。

需要注意的点就是:

本地要有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秒左右……其实无伤大雅。

这里友情提示一下新手小伙伴,别每下载一个网页实例化一个webdriver(Firefox or Chrome)然后就close()掉,实例化webdriver的时间也是时间~推荐将下载器做成单例类或将webdirver做类变量。

Selenium+Headless Chrome

这个跟上边大同小异,我没试,传送门:

PhantomJS在Selenium中被标记为过时的应对措施 Getting Started with Headless Chrome

推荐阅读