你如何 运行 headless chrome 和在 python 中使用 selenium 的代理?

How do you run headless chrome and a proxy using selenium in python?

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

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

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

像这样:

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)

最简单的方法如下所示。将任何 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()