Selenium 不再支持 PhantomJS 的解决办法

震惊!Selenium分手PhantomJS





背景

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

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

运用我考了五遍才飘过的六级英语定睛一看,这个意思是说,新版本的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('http://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()
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

win10和ubuntu下我都测试了没问题,从前实例化一个PhantomJS大约3秒,Headless Firefox的话,7秒左右……其实无伤大雅。

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

Selenium+Headless Chrome

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

碎碎念

上面提到的那首歌中的反対此处是相反的意思,不是汉语的反对,但是,真的好来感~

第一段中提到的今天现在已经成昨天了,又到情人节了哎,好像去年情人节的时候也写了一篇博客吧,去年也是像现在一样单身吧……怎么说着说着眼泪就留下来了呢……






背景

猜你喜欢

转载自blog.csdn.net/HeatDeath/article/details/80278266