python中使用selenium

在使用selenium之前,我们得做一些工作

Firefox浏览器

得下载geckodriver

官网传送门
同时在下载页面详细阅读匹配的firefox版本号与geckodriver版本等信息

否则会报错:

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

然后编辑程序:

from selenium import webdriver

browser = webdriver.Firefox(executable_path = 'D:\SoftWare\geckodriver-v0.21.0-win64\geckodriver.exe')
browser.get('http://www.baidu.com/')

如果出现错误:

selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities

考虑升级浏览器版本


Chrome浏览器

得下载chromedriver

下载传送门

这个下载得先查看 LATEST_RELEASE ,然后下载最新版(因为版本号最大的不一定是最新的)

否则会报错:

selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home

编辑程序:

from selenium import webdriver

browser = webdriver.Chrome(executable_path = "D:\SoftWare\chromedriver_win32\chromedriver.exe")
browser.get('http://www.baidu.com/')

最后

  1. executable_path 的值为你保存的位置。
  2. 如果想要省略 executable_path ,考虑将其值添加到环境变量中。或者将 exe 程序复制到python程序的根目录下,比如说C:\Program Files\Python36\geckodriver.exe 。然后重新打开你的开发环境。(复制到python的根目录亲测有效)
  3. 如果出现错误:
TypeError: get() missing 1 required positional argument: 'url'

问题可能出在 webdriver.Chrome() 的括号你忘写了。

猜你喜欢

转载自blog.csdn.net/sinat_41104353/article/details/81588952