chromedriver + headless + proxy

这个时刻必须写个博客记录一下!!!

 

问题:爬取某网站需要用到 chromedriver + mitmproxy , 但是有个致命的问题就是加入headless和proxy参数后,代理一直会出错,其实就是证书的问题。

 

解决:根据以上问题,进行了很多搜索,测试。 但是有很多版本的答案其实都是不能用的,问题还是没有得到解决。最终在chromium上找到了一个标准答案。下面的代码转自:https://bugs.chromium.org/p/chromium/issues/detail?id=721739#c60

now we can use mitmproxy and chrome headless
-------------------------
from selenium import webdriver
from pyvirtualdisplay import Display
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

#_____________________基本设定___________________________
CHROME_DRIVER_PATH = r'/usr/bin/chromedriver' 
PROXY = "http://127.0.0.1:8080"
#_____________________启动参数___________________________
options = webdriver.ChromeOptions()
options.add_argument('--headless')  
options.add_argument('--disable-gpu')  
options.add_argument("window-size=1024,768")  
options.add_argument("--no-sandbox")

#_____________________代理参数___________________________
desired_capabilities = options.to_capabilities()
desired_capabilities['acceptSslCerts'] = True
desired_capabilities['acceptInsecureCerts'] = True
desired_capabilities['proxy'] = {
    "httpProxy": PROXY,
    "ftpProxy": PROXY,
    "sslProxy": PROXY,
    "noProxy": None,
    "proxyType": "MANUAL",
    "class": "org.openqa.selenium.Proxy",
    "autodetect": False,
}
#_____________________启动浏览器___________________________
driver = webdriver.Chrome(
    chrome_options=options, 
    executable_path=CHROME_DRIVER_PATH,
    desired_capabilities = desired_capabilities,
                         )

for i in range(1):
    driver.get('https://www.iplocation.net')
    contant = driver.page_source
    driver.save_screenshot('hello.png')
    print(contant)
    driver.close()
    driver.quit()

mitmdump -p 8080

 

注: 大家转载的话,记得标注下来源。   写这篇博客的目的第一是为了给自己看,以防以后会忘   第二是给有需要的人看,因为资源实在太少了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值