Selenium 使用 Python - Geckodriver 可执行文件需要在 PATH 中

Selenium using Python - Geckodriver executable needs to be in PATH

我是编程新手,大约两个月前开始使用 Python,我正在研究 Sweigart 的 Automate the Boring Stuff with Python 文本。我正在使用 IDLE 并且已经安装了 Selenium 模块和 Firefox 浏览器。

每当我尝试 运行 webdriver 函数时,我得到这个:

from selenium import webdriver
browser = webdriver.Firefox()

异常:

Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x00000249C0DA1080>>
Traceback (most recent call last):
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 163, in __del__
    self.stop()
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 135, in stop
    if self.process is None:
AttributeError: 'Service' object has no attribute 'process'
Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x00000249C0E08128>>
Traceback (most recent call last):
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 163, in __del__
    self.stop()
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 135, in stop
    if self.process is None:
AttributeError: 'Service' object has no attribute 'process'
Traceback (most recent call last):
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 64, in start
    stdout=self.log_file, stderr=self.log_file)
  File "C:\Python\Python35\lib\subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "C:\Python\Python35\lib\subprocess.py", line 1224, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

在处理上述异常的过程中,又发生了异常:

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    browser = webdriver.Firefox()
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 135, in __init__
    self.service.start()
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 71, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

我想我需要为 geckodriver 设置路径,但我不确定如何设置,那么我该怎么做呢?

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

First of all you will need to download latest executable geckodriver from here to run latest Firefox using Selenium

实际上,Selenium 客户端绑定试图从系统 PATH 中找到 geckodriver 可执行文件。您需要将包含可执行文件的目录添加到系统路径。

  • 在 Unix 系统上,如果您使用 Bash-compatible shell,您可以执行以下操作将其附加到系统的搜索路径中:

      export PATH=$PATH:/path/to/directory/of/executable/downloaded/in/previous/step
    
  • 在 Windows 上,您需要更新 Path 系统变量以将完整目录路径添加到可执行文件 geckodriver manually or command line **(将可执行的 geckodriver 添加到系统 PATH 后不要忘记重新启动系统以生效)**。原理和Unix一样。

现在您可以运行您的代码,就像您正在做的一样:-

from selenium import webdriver

browser = webdriver.Firefox()

selenium.common.exceptions.WebDriverException: 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

异常清楚地表明您在其他位置安装了 Firefox,而 Selenium 试图找到 Firefox 并从默认位置启动,但找不到它。您需要明确提供 Firefox 安装的二进制位置才能启动 Firefox,如下所示:-

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

binary = FirefoxBinary('path/to/installed firefox binary')
browser = webdriver.Firefox(firefox_binary=binary)

https://github.com/mozilla/geckodriver/releases

对于Windows:

从 GitHub 下载文件,解压缩,然后将其粘贴到 Python 文件中。它对我有用。

https://github.com/mozilla/geckodriver/releases

对于我来说,我的路径路径是:

C:\Users\MYUSERNAME\AppData\Local\Programs\Python\Python39

这个步骤 解决了 我在 Ubuntu 和 Firefox 50 上的问题。

  1. 下载geckodriver

  2. 将 geckodriver 复制到文件夹 /usr/local/bin

不需要需要添加:

firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
firefox_capabilities['binary'] = '/usr/bin/firefox'
browser = webdriver.Firefox(capabilities=firefox_capabilities)

在 Selenium/Python 上发表的 none 书籍和 Google 对这个问题的大部分评论都没有清楚地解释设置它的路径逻辑,这真是令人遗憾在 Mac 上(一切都是 Windows!)。 YouTube 视频都是在您获得路径设置的“之后”获取的(在我看来,这是一种廉价的出路!)。因此,对于优秀的 Mac 用户,请使用以下内容编辑您的 Bash 路径文件:

touch ~/.bash_profile; open ~/.bash_profile*

然后添加类似这样的路径....

# Setting PATH for geckodriver
PATH=“/usr/bin/geckodriver:${PATH}”
export PATH

# Setting PATH for Selenium Firefox
PATH=“~/Users/yourNamePATH/VEnvPythonInterpreter/lib/python2.7/site-packages/selenium/webdriver/firefox/:${PATH}”
export PATH

# Setting PATH for executable on Firefox driver
PATH=“/Users/yournamePATH/VEnvPythonInterpreter/lib/python2.7/site-packages/selenium/webdriver/common/service.py:${PATH}”
export PATH*

这对我有用。

解决了这个问题,但它没有解释为什么 Automate the Boring Stuff with Python 不包括这些步骤。

这是因为本书基于 Selenium 2.x,并且该系列的 Firefox 驱动程序不需要 Gecko 驱动程序。在开发 Selenium 时,驱动浏览器的 Gecko 接口不可用。

latest version in the Selenium 2.x series is 2.53.6 (see e.g. these answers,为了更容易查看版本。

2.53.6 version page doesn't mention Gecko at all. But since version 3.0.2 the documentation explicitly states您需要安装Gecko驱动

如果在升级(或安装在新系统上)之后,您之前(或在您的旧系统上)运行良好的软件不再运行并且您很着急,请将 Selenium 版本固定在您的 virtualenv 中通过

pip install selenium==2.53.6

当然,开发的长期解决方案是使用最新版本的 selenium 设置一个新的 virtualenv,安装 Gecko 驱动程序并测试一切是否仍按预期工作。

但是主要版本的提升可能会引入其他 API 本书未涵盖的更改,因此您可能希望坚持使用较旧的 Selenium,直到您有足够的信心可以解决两者之间的任何差异Selenium 2 和 Selenium 3 API 你自己。

我实际上发现您可以使用最新的 geckodriver 而无需将其放入系统路径。目前我正在使用

https://github.com/mozilla/geckodriver/releases/download/v0.12.0/geckodriver-v0.12.0-win64.zip

火狐 50.1.0

Python 3.5.2

硒 3.0.2

Windows 10

我正在 运行安装 VirtualEnv(我使用 PyCharm 管理它,我假设它使用 Pip 安装所有东西)。

在下面的代码中,我可以使用 executable_path 参数为 geckodriver 使用特定路径(我通过查看 Lib\site-packages\selenium\webdriver\firefox\webdriver.py )。请注意,我怀疑调用 webdriver 时参数参数的顺序很重要,这就是为什么 executable_path 在我的代码中排在最后(最右边的倒数第二行)。

您可能还注意到我使用自定义 Firefox 配置文件来绕过 sec_error_unknown_issuer 问题,如果您正在测试的站点具有不受信任的证书,您将 运行 进入该问题。参见 How to disable Firefox's untrusted connection warning using Selenium?

调查后发现 Marionette 驱动程序不完整且仍在进行中,并且设置各种功能或配置文件选项以关闭或设置证书都不起作用。所以使用自定义配置文件更容易。

无论如何,这是我如何让 geckodriver 在不在路径中工作的代码:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True

#you probably don't need the next 3 lines they don't seem to work anyway
firefox_capabilities['handleAlerts'] = True
firefox_capabilities['acceptSslCerts'] = True
firefox_capabilities['acceptInsecureCerts'] = True

# In the next line I'm using a specific Firefox profile because
# I wanted to get around the sec_error_unknown_issuer problems with the new Firefox and Marionette driver
# I create a Firefox profile where I had already made an exception for the site I'm testing
# see https://support.mozilla.org/en-US/kb/profile-manager-create-and-remove-firefox-profiles#w_starting-the-profile-manager

ffProfilePath = 'D:\Work\PyTestFramework\FirefoxSeleniumProfile'
profile = webdriver.FirefoxProfile(profile_directory=ffProfilePath)
geckoPath = 'D:\Work\PyTestFramework\geckodriver.exe'
browser = webdriver.Firefox(firefox_profile=profile, capabilities=firefox_capabilities, executable_path=geckoPath)
browser.get('http://whosebug.com')

这帮我解决了。

from selenium import webdriver
driver = webdriver.Firefox(executable_path=r'your\path\geckodriver.exe')
driver.get('http://inventwithpython.com')

步骤Mac

简单的解决方案是下载 GeckoDriver 并将其添加到您的系统路径中。您可以使用以下两种方法之一:

短方法

  1. 下载解压Geckodriver.

  2. 在启动驱动程序时提及路径:

     driver = webdriver.Firefox(executable_path='/your/path/to/geckodriver')
    

长方法

  1. 下载解压Geckodriver.

  2. 打开 .bash_profile。如果您还没有创建它,您可以使用以下命令创建它:touch ~/.bash_profile。然后使用:open ~/.bash_profile

    打开它
  3. 考虑到 GeckoDriver 文件存在于您的下载文件夹中,您可以将以下行添加到 .bash_profile 文件中:

     PATH="/Users/<your-name>/Downloads/geckodriver:$PATH"
     export PATH
    

这样您就可以将 GeckoDriver 的路径附加到您的系统路径中。这会告诉系统在执行您的 Selenium 脚本时 GeckoDriver 所在的位置。

  1. 保存.bash_profile并强制执行。这会立即加载值而无需重新启动。为此,您可以 运行 以下命令:

source ~/.bash_profile

  1. 就是这样。您 完成了 !您现在可以 运行 Python 脚本。

macOS v10.12.1 (Sierra) 和 Python 2.7.10 上,这对我有用:

def download(url):
    firefox_capabilities = DesiredCapabilities.FIREFOX
    firefox_capabilities['marionette'] = True
    browser = webdriver.Firefox(capabilities=firefox_capabilities,
                                executable_path=r'/Users/Do01/Documents/crawler-env/geckodriver')
    browser.get(url)
    return browser.page_source

在 Raspberry Pi 我必须从 ARM 驱动程序创建它并在文件 webdriver.py:

中设置 geckodriver 和日志路径
sudo nano /usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py
def __init__(self, firefox_profile=None, firefox_binary=None,
             timeout=30, capabilities=None, proxy=None,
             executable_path="/PATH/gecko/geckodriver",
             firefox_options=None,
             log_path="/PATH/geckodriver.log"):

Selenium 在他们的 DESCRIPTION.rst 文件中回答了这个问题:

Drivers
=======

Selenium requires a driver to interface with the chosen browser. Firefox, for example, requires geckodriver <https://github.com/mozilla/geckodriver/releases>_, which needs to be installed before the below examples can be run. Make sure it's in your PATH, e. g., place it in /usr/bin or /usr/local/bin.

Failure to observe this step will give you an error `selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

基本上只需下载 geckodriver,解压缩并将可执行文件移动到您的 /usr/bin 文件夹。

我正在使用 Windows 10,这对我有用:

  1. here 下载 geckodriver。为您使用的计算机下载正确的版本。
  2. 解压缩您刚刚下载的文件和cut/copy其中包含的“.exe”文件
  3. 导航到 C:{您的 python 根文件夹}。我的是 C:\Python27。将 geckodriver.exe 文件粘贴到此文件夹中。
  4. 重新启动您的开发环境。
  5. 再次尝试 运行 代码。它现在应该可以工作了。

为 Selenium 设置 geckodriver Python:

需要使用FirefoxDriver设置geckodriver路径,如下代码:

self.driver = webdriver.Firefox(executable_path = 'D:\Selenium_RiponAlWasim\geckodriver-v0.18.0-win64\geckodriver.exe')

下载适合您的 geckodriver OS(来自 https://github.com/mozilla/geckodriver/releases)→ 将其解压到您选择的文件夹中 → 如上所述正确设置路径。

我在 Windows 10.

上使用 Python 3.6.2 和 Selenium WebDriver 3.4.3

设置geckodriver的另一种方法:

i) 只需将 geckodriver.exe 粘贴到 /Python/Scripts/ 下(在我的例子中,文件夹是:C:\Python36\Scripts
ii) 现在编写如下简单代码:

self.driver = webdriver.Firefox()

访问 Gecko Driver 并从 下载 部分获取 Gecko 驱动程序的 URL。

克隆此存储库:https://github.com/jackton1/script_install.git

cd script_install

运行

./installer --gecko-driver https://github.com/mozilla/geckodriver/releases/download/v0.18.0/geckodriver-v0.25.0-linux64.tar.gz

在已安装 Homebrew 的 macOS 上,您可以简单地 运行 终端命令:

brew install geckodriver

因为 Homebrew 已经扩展了 PATH,所以不需要修改任何启动脚本。

Windows最简单的方法!

here 下载最新版本的 geckodriver。将 geckodriver.exe 文件添加到 Python 目录(或任何其他已在 PATH 中的目录) .这应该可以解决问题(已在 Windows 10 上进行测试)。

我正在使用Windows 10和Anaconda 2。我尝试设置系统路径变量,但没有成功。然后我简单地将 geckodriver.exe 文件添加到 Anaconda 2/Scripts 文件夹中,现在一切正常。

对我来说,路径是:

C:\Users\Bhavya\Anaconda2\Scripts

一些额外的input/clarification:

以下足以作为 Windows 7、Python 3.6 和 Selenium 3.11 的解决方案:

dsalaj's note 对于 Unix 的另一个答案也适用于 Windows;可以避免在 Windows 级别修改 PATH 环境变量并重新启动 Windows 系统。

(1) 下载 geckodriver(如本线程前面所述)并将(解压缩的)geckdriver.exe 放在 X:\Folder\of\your\choice

(2) Python 代码示例:

import os;
os.environ["PATH"] += os.pathsep + r'X:\Folder\of\your\choice';

from selenium import webdriver;
browser = webdriver.Firefox();
browser.get('http://localhost:8000')
assert 'Django' in browser.title

备注:

(1)以上代码打开指定URL.

的Firefox浏览器可能需要10秒左右

(2) 如果在指定 URL 处没有服务器 运行 或提供标题包含字符串 [=] 的页面,Python 控制台将显示以下错误29=]:

selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=connectionFailure&u=http%3A//localhost%3A8000/&c=UTF-8&f=regular&d=Firefox%20can%E2%80%9

如果您正在使用 Anaconda, all you have to do is activate your virtual environment and then install geckodriver using the following command:

    conda install -c conda-forge geckodriver

For Windows users

按原样使用原始代码:

from selenium import webdriver
browser = webdriver.Firefox()
driver.get("https://www.google.com")

然后从以下位置下载驱动程序:mozilla/geckodriver

放在固定路径(永久)...作为例子,我把它放在:

C:\Python35

然后进入系统的环境变量。在“系统变量”的网格中查找 Path 变量并添加:

;C:\Python35\geckodriver

geckodriver,不是geckodriver.exe

如果要在 Windows10 上添加驱动程序路径:

  1. 右键单击“此电脑”图标和select“属性”

  2. 点击“高级系统设置”

  3. 点击屏幕底部的“环境变量”

  4. 在“用户变量”部分突出显示“路径”并单击“编辑”

  5. 通过单击“新建”并输入要添加的驱动程序的路径并按回车键,将路径添加到变量。

  6. 输入路径后,点击“确定”

  7. 一直点击“确定”直到关闭所有屏幕

Ubuntu 18.04+ 和最新版本的 geckodriver

这也适用于其他 Unix-like 品种。

export GV=v0.30.0
wget "https://github.com/mozilla/geckodriver/releases/download/$GV/geckodriver-$GV-linux64.tar.gz"
tar xvzf geckodriver-$GV-linux64.tar.gz
chmod +x geckodriver
sudo cp geckodriver /usr/local/bin/

Mac更新为:

geckodriver-$GV-macos.tar.gz
from webdriverdownloader import GeckoDriverDownloader # vs ChromeDriverDownloader vs OperaChromiumDriverDownloader
gdd = GeckoDriverDownloader()
gdd.download_and_install()
#gdd.download_and_install("v0.19.0")

这将使您找到 Windows 上 gekodriver.exe 的路径。

from selenium import webdriver
driver = webdriver.Firefox(executable_path=r'C:\Users\username\\bin\geckodriver.exe')
driver.get('https://www.amazon.com/')

我看到讨论仍在讨论通过下载二进制文件并手动配置路径来设置 geckodriver 的旧方法。

这可以使用 webdriver-manager

自动完成
pip install webdriver-manager

现在问题中的上述代码只需进行以下更改即可工作,

from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager

driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
  1. 确保您拥有正确版本的驱动程序 (geckodriver),x86 或 64。
  2. 确保您正在检查正确的环境。例如,作业在 Docker 容器中 运行,而在主机 OS.
  3. 上检查环境

如果你使用虚拟环境和Windows10(可能其他系统也一样),你只需要将geckodriver.exe放入你的虚拟环境目录下的如下文件夹:

...\my_virtual_env_directory\Scripts\geckodriver.exe

考虑安装容器化的 Firefox:

docker pull selenium/standalone-firefox
docker run --rm -d -p 5555:4444 --shm-size=2g selenium/standalone-firefox

连接使用 webdriver.Remote:

driver = webdriver.Remote('http://localhost:5555/wd/hub', DesiredCapabilities.FIREFOX)
driver.set_window_size(1280, 1024)
driver.get('https://toolbox.googleapps.com/apps/browserinfo/')
driver.save_screenshot('info.png')

对我来说,在同一环境中安装 geckodriver 就足够了:

brew install geckodriver

并且代码未更改:

from selenium import webdriver
browser = webdriver.Firefox()

也可以执行 echo PATH (Linux),只需将 geckodriver 移动到您喜欢的文件夹即可。如果系统(非虚拟环境)文件夹是目标,则驱动程序将可全局访问。

如果你在 Linux

上,你可以使用一个简单的命令来解决这个问题
  1. 首先,下载(https://github.com/mozilla/geckodriver/releases)并解压 ZIP 文件

  2. 打开解压的文件夹

  3. 从文件夹(提取后 geckodriver 文件所在的位置)打开终端

  4. 现在 运行 在您的终端上使用这个简单的命令将 geckodriver 复制到正确的文件夹中:

     sudo cp geckodriver /usr/local/bin
    

在 Windows 10 上,我可以下载 geckodriver.exe。我只需要更新 Firefox。

下面我使用的代码:

from selenium import webdriver
driver = webdriver.Firefox(
    executable_path=r'C:\Users\Usuario\Desktop\Automate the boring stuff with python exercises\Web Scraping\geckodriver.exe')
driver.get('http://inventwithpython.com')

geckodriver默认没有安装。

geckodriver

输出:

Command 'geckodriver' not found, but it can be installed with:

sudo apt install firefox-geckodriver

下面的命令不仅会安装它,还会把它放在可执行文件中 PATH.

sudo apt install firefox-geckodriver

一步解决问题。我有和你完全一样的错误,我一安装它就消失了。来试试吧。

which geckodriver

输出:

/usr/bin/geckodriver

geckodriver

输出:

1337    geckodriver    INFO    Listening on 127.0.0.1:4444
^C

这个错误信息...

FileNotFoundError: [WinError 2] The system cannot find the file specified

...表示您的程序无法找到指定的文件,并且在处理异常时发生以下异常:

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

... 这意味着您的程序无法在 initiating/spawnning 新的 浏览上下文 过程中找到 GeckoDriverFirefox 浏览器 会话。


您可以通过keyexecutable_path下载最新的GeckoDriver from mozilla / geckodriver, unzip/untar and store the GeckoDriver binary/executable anywhere with in your system passing the absolute path of the 如下:

from selenium import webdriver

driver = webdriver.Firefox(executable_path='/path/to/geckodriver')
driver.get('http://google.com/')

如果 未安装在默认位置(即安装在自定义位置),您还需要通过属性 binary_location 传递 firefox 二进制文件的绝对路径如下:

# An Windows example
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'
driver = webdriver.Firefox(firefox_options=options, executable_path=r'C:\WebDrivers\geckodriver.exe')
driver.get('http://google.com/')

在 Ubuntu

上安装 geckodriver 的手动步骤
  • 访问https://github.com/mozilla/geckodriver/releases

  • 下载最新版“geckodriver-vX.XX.X-linux64.tar.gz”

  • 解压 tar球 (tar -xvzf geckodriver-vX.XX.X-linux64.tar.gz)

  • 给geckodriver赋予可执行权限(chmod +x geckodriver)

  • 将 geckodriver 二进制文件移动到 /usr/local/bin 或系统路径上的任何位置。

在 Ubuntu 上安装 geckodriver 的脚本:

#!/bin/bash

INSTALL_DIR="/usr/local/bin"

json=$(curl -s https://api.github.com/repos/mozilla/geckodriver/releases/latest)
url=$(echo "$json" | jq -r '.assets[].browser_download_url | select(contains("linux64"))')
curl -s -L "$url" | tar -xz
chmod +x geckodriver
sudo mv geckodriver "$INSTALL_DIR"
echo "installed geckodriver binary in $INSTALL_DIR"

此答案完全复制自: Corey Goldberg's answer to How to install geckodriver in Ubuntu?

我把路径添加到“环境变量”后解决了这个问题。

from selenium import webdriver

browser = webdriver.Firefox(executable_path='C:\ProgramData\Anaconda3\geckodriver.exe')

url = "https://github.com"

browser.close()

对于版本 Ubuntu 16.04 (Xenial Xerus) 及更高版本,您可以:

对于 Firefox:
sudo apt-get install firefox-geckodriver

对于Chrome:
sudo apt-get install chromium-chromedriver

MacBook 用户:

第 1 步:

打开this link and copy that Homebrew路径,粘贴到终端并安装。

第 2 步:

brew install geckodriver

第 3 步:

pip install webdriver-manager

避免错误的新方法是使用 Conda 环境。

使用 conda install -c conda-forge geckodriver,您无需向路径添加任何内容或编辑代码!