Headless Chrome (with selenium) 不能通过代理服务器请求,但是请求可以吗?

Yih*_*hou 5 python proxy selenium selenium-webdriver google-chrome-headless

我正在尝试将 Chrome 与 python webdriver + selenium 一起使用,但是当我设置代理设置时它似乎不起作用?这是我的代码:

from selenium import webdriver

PROXY = 'http://42.115.88.220:53281'
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument('--proxy-server=%s' % PROXY)
chromeOptions.add_argument("ignore-certificate-errors")

wbe = webdriver.Chrome(options=chromeOptions)
wbe.get("http://icanhazip.com")
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,浏览器给了我:“无法访问此站点”错误:

无法访问此站点

连接被重置。
尝试:

  • 检查连接
  • 检查代理和防火墙
  • 运行 Windows 网络诊断

ERR_CONNECTION_RESET

一些努力:我尝试使用我的代理服务器进行请求,并且可以正常工作。所以应该不是我的代理服务器的问题。

import requests

proxies = {"http": "http://42.115.88.220:53281"}
r = requests.get("http://icanhazip.com", proxies = proxies)
print (r.status_code)
Run Code Online (Sandbox Code Playgroud)

这给了我 200 的响应代码和良好的响应。

目标:我的最终目标是使用 PROXY 构建一个带有无头 chrome 的网络爬虫,所以现在我首先测试一个非无头的网络爬虫。但这个 PROXY 问题似乎有问题。

如果有人能帮我解决这个问题,我将不胜感激!!!

小智 0

尝试这个。对我来说,您似乎使用了错误类型的无头模式。对于 chrome selenium 浏览器,正确设置 --headless 参数非常重要。

from selenium import webdriver

PROXY = 'http://ip:port'
chromeOptions = webdriver.ChromeOptions() 
chromeOptions.add_argument('--proxy-server=%s' % PROXY) 
chromeOptions.add_argument("ignore-certificate-errors")
# Headless mode for chrome browser
chromeOptions.add_argument('--headless=chrome')
wbe = webdriver.Chrome('your_driver_path_or_service', options=chromeOptions) 
wbe.get("http://icanhazip.com")
print(wbe.title)
print(wbe.current_url)
print(wbe.page_source)

# Output:
# http://icanhazip.com/
# <html><head><meta name="color-scheme" content="light dark"></head><body><pre 
# style="word-wrap: break-word; white-space: pre-wrap;">your ip
# </pre></body></html>
Run Code Online (Sandbox Code Playgroud)