我试图在Google Colab中使用Selenium,但在尝试运行Firefox实例时遇到了一些错误。我关注了以下链接:
- Selenium文档在这里,我尝试了驱动程序管理软件,但我得到了一个错误,说无法找到Firefox的二进制位置。所以我尝试了硬编码定位方法,但我仍然有同样的错误,所以我认为我必须在谷歌colab中安装firefox,但我不知道这是否是正确的方法
这是我的代码:
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.firefox import GeckoDriverManager
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
service = FirefoxService(executable_path= '/content/drive/MyDrive/geckodriver')
driver = webdriver.Firefox(service=service)
这就是整个错误:
SessionNotCreatedException Traceback (most recent call last)
<ipython-input-7-51ea1584f592> in <module>()
1 service = FirefoxService(executable_path= '/content/drive/MyDrive/geckodriver')
----> 2 driver = webdriver.Firefox(service=service)
4 frames
/usr/local/lib/python3.7/dist-packages/selenium/webdriver/remote/errorhandler.py in check_response(self, response)
245 alert_text = value['alert'].get('text')
246 raise exception_class(message, screen, stacktrace, alert_text) # type: ignore[call-arg] # mypy is not smart enough here
--> 247 raise exception_class(message, screen, stacktrace)
248
249 def _value_or_default(self, obj: Mapping[_KT, _VT], key: _KT, default: _VT) -> _VT:
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
编辑
我试着在谷歌colab上安装firefox,我认为一切都是正确的,但当它试图运行firefox时,我在geckodoriver.log上得到了这个输出:
1643070515477 geckodriver INFO Listening on 127.0.0.1:43355
1643070515979 mozrunner::runner INFO Running command: "/usr/bin/firefox" "--marionette" "--headless" "--no-sandbox" "--disable-dev-shm-usage" "--remote-debugging-port" "43945" "-no-remote" "-profile" "/tmp/rust_mozprofileeDGKcf"
src/tcmalloc.cc:283] Attempt to free invalid pointer 0x7fe67e416250
Redirecting call to abort() to mozalloc_abort
这是代码:
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.firefox import GeckoDriverManager
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
service = FirefoxService(executable_path= '/content/drive/MyDrive/geckodriver')
options = webdriver.FirefoxOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Firefox(service= service, options= options)
似乎您正在下载GeckoDriver并将其存储在网络位置,然后安装它:
drive.mount('/content/drive', force_remount=True)
根据多次讨论,GeckoDriver/FirefoxService无法从网络位置启动。
你可以在中找到一些相关的讨论
- CreatePlatformSocket((返回错误:提供了无效的参数。(0x2726(尝试通过网络路径访问chromedriver时
- CreatePlatformSocket((失败:协议不支持地址族,并且无法在AWS Lambda中使用WebDriverManager找到chrome二进制文件
解决方案
因此,一个通用的解决方案是通过将GeckoDriver/Firefox放入主机的本地驱动器来访问它们。