selenium 使用ip代理报错 unknown error: net::ERR_TUNNEL_CONNECTION_FAILED 解决办法

问题描述

在使用 selenium 框架作为爬虫框架进行内容爬取时,难免会用到 ip 代理池。第一次使用 selenium 的 --proxy-server 参数进行代理访问时,我遇到了如下报错:

selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_TUNNEL_CONNECTION_FAILED

报错原因

在 selenium 框架中想使用 ip 代理的方式访问 url,必须先安装selenium-wire 模块,再从 seleniumwire 导入 webdriver 后使用。否则就会报上面的错误。安装方式:

pip install selenium-wire

使用方法

注意:一定要从 seleniumwire 引入 webdriver

#!/usr/bin/python
# -*- coding: utf-8 -*-

# 想使用 ip 代理,必须先安装 selenium-wire 模块,再从 seleniumwire 导入 webdriver
# 否则报错:selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_TUNNEL_CONNECTION_FAILED
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
import random
import time

CHROMEDRIVER_PATH = './chromedriver' # Chrome 驱动存放位置

if __name__ == '__main__':
    """使用无界面模式及 IP 代理模式访问 URL"""

    # Options
    options = webdriver.ChromeOptions()
    options.add_argument('--headless') # 开启无界面模式
    options.add_argument('--disable-gpu') # 禁用显卡
    options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片
    options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36") # 替换UA

	# 此处替换成自己的 IP 代理池
    proxy_arr = [
        '--proxy-server=http://223.112.174.62:9091',
        '--proxy-server=http://183.239.61.167:9091'
    ]
    proxy = random.choice(proxy_arr) # 随机选择一个代理
    options.add_argument(proxy) # 添加代理

    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option("useAutomationExtension", False)
    service = ChromeService(executable_path=CHROMEDRIVER_PATH)
    driver = webdriver.Chrome(service=service, chrome_options=options)

    driver.get("https://www.csdn.net/") # 访问 URL
    time.sleep(3)

	# 查找 ID
    csdn_title = driver.find_element(By.XPATH, '//*[@id="csdn-toolbar"]/div/div/div[1]/div/a/img').get_attribute("title")
    print(csdn_title)

    driver.quit() # 退出

  • 7
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hiwb

您的鼓励是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值