在使用 Selenium 控制 Firefox 浏览器时,需要使用 GeckoDriver。如果你手动下载了 GeckoDriver,可以按照以下步骤指定它的路径:

  1. 在代码中指定路径

geckodriver.exe 文件保存到一个你可以访问到的位置,例如 D:\geckodriver\geckodriver.exe。然后在代码中使用 executable_path 参数指定路径:

from selenium import webdriver

driver = webdriver.Firefox(executable_path='D:/geckodriver/geckodriver.exe')

或者

from selenium.webdriver.firefox.options import Options

options = Options()
options.binary_location = 'C:\Program Files\Mozilla Firefox\firefox.exe'
driver = webdriver.Firefox(options=options, executable_path='D:/geckodriver/geckodriver.exe')
  1. 使用环境变量

在系统环境变量中添加一个名为 GECKODRIVER 的变量,并将值设置为 geckodriver.exe 所在的目录,例如 D:\geckodriver

然后在代码中使用以下代码调用:

from selenium import webdriver
import os

gecko_path = os.getenv('GECKODRIVER')
driver = webdriver.Firefox(executable_path=gecko_path + '/geckodriver.exe')

这样就可以使用环境变量来指定 GeckoDriver 的路径。

无论是代码中指定路径还是使用环境变量,都能够成功使用 GeckoDriver 控制 Firefox 浏览器。

Selenium 使用 GeckoDriver:指定路径的两种方法

原文地址: http://www.cveoy.top/t/topic/nQkR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录