【问题标题】:Using a http proxy with headless firefox in Selenium webdriver in Python在 Python 的 Selenium webdriver 中使用带有无头 firefox 的 http 代理
【发布时间】:2018-06-11 05:18:00
【问题描述】:

我正在使用这样的无头 Firefox:

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

# Set the MOZ_HEADLESS environment variable which casues Firefox to
# start in headless mode.
os.environ['MOZ_HEADLESS'] = '1'

# Select your Firefox binary.
binary = FirefoxBinary('/usr/bin/firefox', log_file=sys.stdout)

# Start selenium with the configured binary.
driver = webdriver.Firefox(firefox_binary=binary)

但现在我想添加一个需要用户/密码的 http 代理。搜索后,我尝试了以下方法:

from selenium.webdriver.common.proxy import Proxy, ProxyType

myProxy = "xx.xx.xx.xx:80"

proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    'httpProxy': myProxy,
    'ftpProxy': myProxy,
    'sslProxy': myProxy,
    'noProxy': '' # set this value as desired
    })

driver = webdriver.Firefox(firefox_binary=binary, proxy=proxy)

我也试过

profile = webdriver.FirefoxProfile() 
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", "xx.xx.xx.xx")
profile.set_preference("network.proxy.http_port", 80)
profile.update_preferences() 
driver=webdriver.Firefox(firefox_binary=binary,firefox_profile=profile)

最后,我尝试将带有凭据的“socksUsername”和“socksPassword”添加到proxy,更多的是出于绝望而不是真正的希望。

不用说这些都不起作用,测试表明请求仍在使用我常用的 IP,而不是代理。

在这种情况下,系统范围的代理也不是一个选项。

http 代理凭据应该放在哪里?如何在无头 Firefox 中使用代理?

测试

driver.get("https://www.ipinfo.io");
driver.find_element_by_xpath('//h4/following-sibling::p').text

【问题讨论】:

  • 你在哪个操作系统上使用这个?
  • 另外你用的是什么类型的代理?
  • 嘿,这个问题已经解决了吗?有人请发布答案

标签: python selenium firefox proxy headless


【解决方案1】:

如果你的代理需要用户名和密码,你必须这样写:

from selenium.webdriver.common.proxy import Proxy, ProxyType

myProxy = "username:password@proxyDomain:proxyPort"

proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    'httpProxy': myProxy,
    'ftpProxy': myProxy,
    'sslProxy': myProxy,
    'noProxy': '' # set this value as desired
    })

driver = webdriver.Firefox(firefox_binary=binary, proxy=proxy)

【讨论】:

    【解决方案2】:

    您可以尝试在以下助记符中设置环境变量“HTTP_PROXY”:

    http://<username>:<password>@<proxy_url>
    

    在代理 url 之前添加以冒号 ':' 分隔的凭据,前面是 '@' 例如

    http://username:password@proxy.com:8080/file.pac
    

    【讨论】:

      【解决方案3】:

      您是否尝试过手动设置配置文件

      ./firefox --ProfileManager
      

      手动设置代理,然后加载您手动设置的配置文件

      from selenium import webdriver
      
      url = "https://mail.google.com"
      fp = webdriver.FirefoxProfile('/Users/<username>/Library/Application Support/Firefox/Profiles/71v1uczn.default')
      
      driver = webdriver.Firefox(fp)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-16
        • 2018-06-15
        • 2013-06-25
        • 2016-12-05
        • 2019-08-07
        • 2014-04-15
        • 1970-01-01
        • 2012-08-24
        相关资源
        最近更新 更多