【问题标题】:How do you run headless chrome and a proxy using selenium in python?如何在 python 中使用 selenium 运行无头 chrome 和代理?
【发布时间】:2018-07-26 13:17:18
【问题描述】:

我的 python 脚本在 selenium 中有无头 chrome 并且功能正常,但是如果可能的话,我如何也可以使用代理?如何将代理主机端口传递给我的无头 chrome 浏览器?

options = webdriver.ChromeOptions()  
options.add_argument('headless')  
browser = webdriver.Chrome(chrome_options=options)

如何将代理主机端口与 selenium 和主要是无头 chrome 一起使用?谢谢!

【问题讨论】:

    标签: python selenium web-scraping proxy headless


    【解决方案1】:

    类似这样的:

    from selenium import webdriver
    from selenium.webdriver.common.proxy import Proxy, ProxyType
    
    
    options = webdriver.ChromeOptions()  
    options.add_argument('headless')
    desired_caps = options.to_capabilities()
    
    prox = Proxy()
    prox.proxy_type = ProxyType.MANUAL
    prox.http_proxy = "ip_addr:port"
    prox.socks_proxy = "ip_addr:port"
    prox.ssl_proxy = "ip_addr:port"
    prox.add_to_capabilities(desired_caps)
    
    
    browser = webdriver.Chrome(desired_capabilities=desired_caps)
    

    【讨论】:

      【解决方案2】:

      最简单的方法如下所示。将任何ip address 放入proxy 变量中以了解其工作原理。 ipport: 分隔。

      from selenium import webdriver
      
      proxy = "94.122.251.105:3128" #test with any ip address which supports `http` as well because the link within the script are of `http`
      
      chrome_options = webdriver.ChromeOptions()
      chrome_options.add_argument('--headless')
      chrome_options.add_argument('--proxy-server={}'.format(proxy))
      driver = webdriver.Chrome(chrome_options=chrome_options)
      
      driver.get('http://www.lagado.com/proxy-test')
      items = driver.find_element_by_css_selector(".main-panel p:nth-of-type(2)").text
      print(items) #it should print out the ip address you are using in the `proxy` variable above
      driver.quit()
      

      【讨论】:

        猜你喜欢
        • 2021-02-22
        • 2015-05-10
        • 1970-01-01
        • 1970-01-01
        • 2023-01-22
        • 2020-12-10
        • 2013-06-09
        • 2023-01-14
        • 2018-07-30
        相关资源
        最近更新 更多