9

ubuntu16.04下,python库selenium使用firefox浏览器无头模式,获取网页内容,geckodri...

 3 years ago
source link: https://blog.popkx.com/ubuntu16-04-use-python-selenium-call-headless-firefox-to-visit-website-page-geckodriver-executable-needs-to-be-in-path/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

ubuntu16.04下,python库selenium使用firefox浏览器无头模式,获取网页内容,geckodriver executable needs to be in PATH

发表于 2018-08-02 22:08:07   |   已被 访问: 525 次   |   分类于:   Python   |   暂无评论

通常各大网站的后台都会有一定的反爬机制,既为了数据安全,也为了减小服务器压力。反爬的手段的方向,都是识别非浏览器客户端,而selenium所做的事情,恰恰是驱动真正的浏览器去执行请求和操作,只不过信号不是来源于鼠标,而是来源于selenium的API(selenium本是一个自动化的测试工具),自然人用户能做的一切,selenium几乎都驱动浏览器取做,无论是否有界面,包括输入、点击、滑动,等等然而到底是鼠标操作的浏览器发起的请求还是API,对于服务端来说,是没有任何差别的。

安装python的selenium库

强大的 selenium 库安装非常简单,只需执行pip install命令即可安装。

sudo pip install selenium

ubuntu16.04 自带浏览器 firefox 驱动下载

一开始也是尝试了 Chrome 浏览器,但是无头模式总是不成功,即使设置了--headless,也依然会有浏览器出现,因此决定使用 ubuntu 自带的 firefox 浏览器。

执行以下脚本:

#encoding=utf8

# 导入selenium的浏览器驱动接口
from selenium import webdriver
# 要想调用键盘按键操作需要引入keys包
from selenium.webdriver.common.keys import Keys
# 导入chrome选项
from selenium.webdriver.firefox.options import Options

# 创建chrome浏览器驱动,无头模式(超爽)
firefox_options = Options()
firefox_options.set_headless()
driver = webdriver.Firefox(firefox_options=firefox_options)
# driver = webdriver.Firefox()
# 加载百度页面
driver.get("http://www.baidu.com/")
# time.sleep(3)
# 获取页面名为wrapper的id标签的文本内容
data = driver.find_element_by_id("wrapper").text
print(data)
# 打印页面标题 "百度一下,你就知道"
print(driver.title)
# 生成当前页面快照并保存
driver.save_screenshot("baidu.png")
# 关闭浏览器
driver.quit()

发现失败了,提示

selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

geckodriver,看其名字,应该是 firefox 的驱动,类似于 chrome 浏览器的 chromedirver,所以下载之,链接:点我下载
然后解压,将其所在路径加入环境变量:

export PATH=/路径:$PATH

再执行,发现成功了。

$ python t.py 
新闻
hao123
地图
视频
贴吧
学术
登录
设置
更多产品
百度
把百度设为主页关于百度About  Baidu百度推广
©2018 Baidu 使用百度前必读 意见反馈 京ICP证030173号  京公网安备11000002000001号 
百度一下,你就知道

阅读更多:   Python


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK