Selenium 脚本中的 Geckodriver 错误。 Geckodriver 安装正确,但我得到 'geckodriver' executable needs to be in PATH

Geckodriver error in Selenium script. Geckodriver is installed correctly, but I get 'geckodriver' executable needs to be in PATH

我不明白为什么 geckodriver 不起作用,为什么路径不存在。我使用 Ubuntu 和 Firefox,我卸载并重新安装了 geckodriver 和 Firefox-geckodriver。我检查了版本并使用 geckodriver 0.30.0 (d372710b98a6 2021-09-16 10:29 +0300)。我已经尝试使用

卸载和安装
wget https://github.com/mozilla/geckodriver/releases/download/v0.30.0/geckodriver-v0.30.0-linux64.tar.gz
tar -xvzf geckodriver-v0.30.0- linux64.tar.gz 
chmod + x geckodriver 
export PATH = $ PATH: / path-to-extracted-file /

我也安装了

sudo apt install firefox-geckodriver

我尝试 运行 这个小脚本,但出现错误:

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

代码

from selenium.webdriver import Firefox
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver

from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
import os

from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
profile_path = '/home/jack/.local/share/torbrowser/tbb/x86_64/tor-browser_en-US/Browser/TorBrowser/Data/Browser/profile.default'

options=Options()
options.set_preference('profile', profile_path)
options.set_preference('network.proxy.type', 1)
options.set_preference('network.proxy.socks', '127.0.0.1')
options.set_preference('network.proxy.socks_port', 9050)
options.set_preference("network.proxy.socks_remote_dns", False)

service = Service('/usr/bin/geckodriver')
driver = Firefox(service=service, options=options)

driver.get("www.google.com")
driver.quit()

下载 GeckoDriver 的 path/location 似乎有些歧义,可能不在 PATH / 默认位置.

@furas 这种情况下,建议最简单的方法是使用 Webdriver Manager.

示例代码:

  • Selenium 3兼容代码:

    from selenium import webdriver
    from webdriver_manager.firefox import GeckoDriverManager
    
    driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
    
  • Selenium 4兼容代码:

    from selenium import webdriver
    from selenium.webdriver.firefox.service import Service
    from webdriver_manager.firefox import GeckoDriverManager
    
    driver = webdriver.Firefox(service=Service(GeckoDriverManager().install()))