首页 > 解决方案 > 使用 Pyinstaller 后无法使用 Selenium-wire 访问网站

问题描述

我需要访问一个网站。为此,我需要使用具有身份验证和特定用户代理的代理。这是代码:

def start_driver(proxy_data, user_agent):
    proxy = (
            proxy_data.get('login') + ':' + proxy_data.get('password') +
            '@' + proxy_data.get('ip') + ':' + proxy_data.get('port')
    )
    executable_path = os.path.abspath(r'assets\geckodriver\driver.exe')
    firefox_binary = os.path.abspath(r'assets\firefox\browser.exe')
    firefox_options = Options()
    capabilities = webdriver.DesiredCapabilities().FIREFOX
    firefox_profile = FirefoxProfile()
    # firefox_options.add_argument('--headless')
    capabilities['pageLoadStrategy'] = 'eager'
    options = {
        'proxy': {
            'http': 'http://' + proxy,
            'https': 'https://' + proxy,
        }
    }
    driver = webdriver.Firefox(
        executable_path=executable_path,
        firefox_binary=firefox_binary,
        seleniumwire_options=options,
        capabilities=capabilities,
        firefox_profile=firefox_profile,
        firefox_options=firefox_options
    )
    driver.header_overrides = {'User-Agent': user_agent}
    return driver

为了确保一切正常,我 ping http://whatsmyuseragent.org/

driver.get('http://whatsmyuseragent.org/')

这部分代码工作正常。但是,当我获得目标网站时:

driver.get('https://domain.tld/')

我收到一个错误:

selenium.common.exceptions.WebDriverException:消息:到达错误页面:about:neterror?e=nssFailure2&u=...

奇怪的是,当我直接通过 PyCharm 运行脚本时 - 一切都很完美。但是在使用pyinstaller以下参数后:

pyinstaller --onefile MyScript.py

Selenium 确实到达http://whatsmyuseragent.org/但无法到达目标网站https://domain.tld

我确实认为问题在于pyinstaller本身,但我真的不明白为什么会发生。我只有两个版本来解释它为什么会发生:

  1. 编译过程中的问题pyinstaller
  2. 目标网站以某种方式不允许 Selenium 访问它(但是为什么 Selenium 在使用 PyCharm 而不是 .exe 文件时可以访问它?)

有什么想法和/或替代品pyinstaller吗?

标签: pythonseleniumgeckodriverseleniumwire

解决方案


如果其他人有这个问题,我找到了解决方案。转到你的 python 文件夹,找到 pyinstaller hooks 文件夹,对我来说是:

https://github.com/wkeeling/selenium-wire/issues/84#issuecomment-624389859

C:\Python37-32\Lib\site-packages\PyInstaller\hooks

创建一个名为的新文件:

钩硒线.py

在里面你需要:

from PyInstaller.utils.hooks import collect_data_files

datas = collect_data_files('seleniumwire')

推荐阅读