【问题标题】:Adding proxy support to Selenium multi session opening script in Python在 Python 中为 Selenium 多会话打开脚本添加代理支持
【发布时间】:2020-08-02 00:36:23
【问题描述】:

我最近制作了一个脚本,允许我创建针对一个 URL 的多个浏览器会话。我想为其添加代理支持,以免在运行时被禁止。我尝试使用 selenium 中的代理库,但它只是被忽略了。 我的问题:在 python 中使用 Selenium 时,如何在此脚本中添加代理支持? (每个会话都会得到一个随机代理) 这是我的代码

【问题讨论】:

    标签: python python-3.x selenium proxy selenium-chromedriver


    【解决方案1】:

    您可以使用stem 库,它允许您在python 中使用Tor。阅读文档here 了解如何使用它。

    您的代码中缺少的两个基本部分如下:

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

    2. chrome_options.add_argument('--proxy-server=#yourproxyhere#'

    3. 托尔!

    在这里你可以看到我是如何设置我的 stem + selenium 项目的:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.common.proxy import Proxy, ProxyType
    from time import sleep
    from stem import Signal
    from stem.control import Controller
    
    #this gives you a new identity 
    with Controller.from_port(port = 9051) as controller:
      controller.authenticate()
      controller.signal(Signal.NEWNYM)
      #set the proxy in selenium to 127.0.0.1:9150 and have your Tor Browser open!
    
    link = 'https://some-link.com' #target url
    prox= 'socks5://127.0.0.1:9150' #Here you connect to your localhost which connects to a Tor network
    #some chrome_options
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--proxy-server=%s' % prox) 
    chrome_options.add_argument("--window-size=400,600") 
    
    
    #the following also deactivates location tracking!
    prefs = {"profile.default_content_setting_values.geolocation" :2}
    chrome_options.add_experimental_option("prefs",prefs)
    
    driver = webdriver.Chrome("path_to_chromedriver", chrome_options=chrome_options)
    driver.get(link)
    

    【讨论】:

    • 嗨,谢谢您的回复,我添加了 selenium.webdriver.common.proxy 并将代理添加到 chrome_options.add_argument,但问题是我不想使用 tor 我会喜欢使用 txt 文件作为代理源,以便使用我购买的私人代理。现在添加了参数,命令提示符显示 --TypeError: add_argument() 接受 2 个位置参数,但给出了 3 个--
    • 我认为问题可能在于您的 chrome_options.add_argument 中有 2 个参数。我永远不会这样做,我编辑了我的原始回复
    • 我看到问题是我设法找到了另一种方法来实现我的目标,代理仍然被忽略,哈哈,需要弄清楚如何解决它。
    【解决方案2】:

    这是我的代码的更新版本,包括新的代理支持元素,我希望它通过 proxies = read_from_txt("proxies.txt") 使用 txt 文件中的代理并使用随机库在它们之间随机旋转:

    感谢您的快速回复,非常感谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-20
      • 2022-11-27
      • 2013-10-04
      • 2021-05-04
      • 2012-07-16
      • 2022-10-23
      • 1970-01-01
      相关资源
      最近更新 更多