Python中Selenium配合Chrome如何在请求头添加Proxy-Authorization
from selenium import webdriver
def create_webdriver():
options = webdriver.ChromeOptions()
options.add_argument(’–User-Agent=xxxx’)
options.add_argument(’–Proxy-Authorization=xxxxx’)
browser = webdriver.Chrome(chrome_options=options)
return browser
def main():
url = ‘http://www.baidu.com’
browser = create_webdriver()
browser.get(url)
chrome 是不允许添加 header 吗,请求的头部并没有我添加的参数。有小伙伴遇到这种问题吗?
Python中Selenium配合Chrome如何在请求头添加Proxy-Authorization
你好 这个问题你解决了吗 我现在也遇到这个问题了 不知道怎么解决
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 创建Chrome选项
chrome_options = Options()
# 设置代理服务器地址和端口
proxy_host = "your_proxy_host"
proxy_port = "your_proxy_port"
proxy_username = "your_username"
proxy_password = "your_password"
# 构建代理URL(包含认证信息)
proxy_url = f"http://{proxy_username}:{proxy_password}@{proxy_host}:{proxy_port}"
# 设置代理
chrome_options.add_argument(f'--proxy-server={proxy_url}')
# 创建WebDriver实例
driver = webdriver.Chrome(options=chrome_options)
# 测试访问
driver.get("https://httpbin.org/headers")
print(driver.page_source)
# 关闭浏览器
driver.quit()
如果你的代理服务器要求Proxy-Authorization头,但上面的基础认证方式不工作,可以用这个更直接的方法:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.proxy import Proxy, ProxyType
import base64
# 创建代理对象
proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = f"{proxy_host}:{proxy_port}"
proxy.ssl_proxy = f"{proxy_host}:{proxy_port}"
# 编码认证信息
credentials = f"{proxy_username}:{proxy_password}"
encoded_credentials = base64.b64encode(credentials.encode()).decode()
# 添加认证头
capabilities = webdriver.DesiredCapabilities.CHROME
proxy.add_to_capabilities(capabilities)
# 这里需要修改Chrome的启动参数来添加自定义头
chrome_options = Options()
chrome_options.add_argument(f'--proxy-server=http://{proxy_host}:{proxy_port}')
# 创建driver时传入capabilities
driver = webdriver.Chrome(
options=chrome_options,
desired_capabilities=capabilities
)
# 通过执行CDP命令添加Proxy-Authorization头
driver.execute_cdp_cmd('Network.setExtraHTTPHeaders', {
'headers': {
'Proxy-Authorization': f'Basic {encoded_credentials}'
}
})
# 测试
driver.get("https://httpbin.org/headers")
print(driver.page_source)
driver.quit()
注意:第二种方法需要Chrome 59+版本支持CDP协议。如果还有问题,可能需要考虑用undetected-chromedriver或者直接修改Chrome启动参数。
总结:用基础认证格式的代理URL最简单。
没解决呢,可以试试 phantomjs
额 我的需求没法使用 phantomjs 哪个站点可以识别 phantomjs 被反了

