
GeckoDriver+Selenium+Try Xpath插件安装
·
确认Firefox版本号的步骤
确认Firefox版本后,通过selenium库模拟Firefox火狐浏览器时:
(1)需要在浏览器驱动geckodriver.exe;
(2)可以安装Try Xpath插件更好地定位网页元素
一、下载并安装geckodriver
(1)下载网址:
https://github.com/mozilla/geckodriver/releases
对应版本如下:
解压zip文件得到 geckodriver.exe文件
(2)将下载的geckodriver.exe文件拷贝到对应位置
将下载的geckodriver.exe文件分别拷贝到Anaconda安装目录下的Scripts子目录中,和Firefox浏览器的安装目录里面(mozilla firefox目录下),在我电脑的位置如下:
I.Anaconda安装目录下的Scripts子目录
D:\Program Files\Anaconda3\installation location\Scripts\geckodriver.exe
II.Firefox浏览器的安装目录里
D:\Program Files\Firefox\installation location\Mozilla Firefox\geckodriver.exe
(3)配置环境变量Path,把以下内容加入环境变量Path是最关键的,否则会报错
D:\Program Files\Firefox\installation location\Mozilla Firefox\geckodriver.exe
如图:
在没设置环境Path时,我曾遇到过以下报错:
I.报错1
SessionNotCreatedException: Message: Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line
会话无法打开异常:返回信息:预期的浏览器二进制文件位置,但无法在默认位置找到二进制文件,没有提供“moz:firefoxOptions.binary”(火狐选项里的二进制)方法,并且在命令行没有设置二进制标志
在这个地方,我们也可以检查一下,在cmd输入:where geckodriver,查看结果
II.报错2
InvalidArgumentException: Message: binary is not a Firefox executable
无效参数异常:返回信息:二进制文件不是火狐浏览器能执行的文件
III.报错3
WebDriverException: Message: Service D:\Program Files\Firefox\installation location\Mozilla Firefox\firefox.exe unexpectedly exited. Status code was: 0
网页驱动异常:返回信息:服务D:\Program Files\Firefox\installation location\Mozilla Firefox\firefox.exe以外退出,状态码为0
总结以上报错的所有原因: 找不到浏览器
解决方案:当设置好环境变量后,便不再报错了
(4)代码测试
from selenium import webdriver
# 如果firefox没有安装在默认位置,就要手动指定位置
location = r'D:\Program Files\Firefox\installation location\Mozilla Firefox\geckodriver.exe'
driver = webdriver.Firefox(firefox_binary=location)
# 请求页面
driver.get("https://www.xiaoying.com/user/login")
# 通过css选择器获取相应元素
jUsername = driver.find_element_by_css_selector('.jUsername')
# 填写前先清空
jUsername.clear()
# 模拟系统按键
jUsername.send_keys("18812345678")
jPassword = driver.find_element_by_css_selector('.jPassword')
jPassword.clear()
jPassword.send_keys("pass123456")
jSubmit = driver.find_element_by_css_selector('.jSubmit')
# 模拟点击登录按钮(这里帐号密码是乱填的,所以是登录不成功的)
jSubmit.click()
driver.close()
二、火狐浏览器Try Xpath插件安装
(1)打开 火狐浏览器,点击右上角“更多”,选择“更多工具”,打开 “面向开发者的扩展”,搜索:Try Xpath
(2)点击 Try Xpath
(3)在跳转的页面里点击“添加到Firefox”
(4)点击小窗口弹出的“添加”
(5)成功如图,在浏览器右上角显示TX
三、参考网址
(1)下载geckodriver.exe网址
GeckoDriver+Selenium+Python的安装和使用 - 船长博客 - 博客园
(2)拷贝geckodriver.exe 到另外位置
selenium模块和geckodriver安装方法_qq_27428793的博客-CSDN博客
(3)selenium代码测试
python+selenium+firefox使用例子_LiXianlin's Blog-CSDN博客_firefox selenium
更多推荐
所有评论(0)