admin管理员组

文章数量:1571378

最近在写爬虫时,使用selenium时遇到一个问题,不使用代理时是可以访问,可以抓取到数据的,使用代理ip之后无法加载网页,

代码如上,使用代理之后就无法访问网页,查了很多资料,都是说'--proxy-server=http://' + self.proxy将"--"换成'-',还有的说的ip和port之间的':'切换成中的':',切换为中文之后确实是可以访问,但是这是错的,

ip还是本机IP,没有使用代理,后来各种调试,终于搞定,'--proxy-server=http://' + self.proxy修改为'--proxy-server=' + self.proxy即可,前面的http://会自动补全,不需要添加,修改后的代码如下:

# -*- coding: utf-8 -*-
import time
import random
from selenium import webdriver


class SetProxyModel():
    test_url = "http://httpbin/ip"

    def __init__(self):
        self.options = webdriver.ChromeOptions()
        self.options.add_argument(
            'user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36"')
        # 设置代理
        self.proxy = '125.87.104.255:22015'
        self.options.add_argument('--proxy-server=' + self.proxy)
        self.driver = webdriver.Chrome(
            executable_path=r'C:\Users\asus\Envs\lawyer\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe',
            options=self.options)
        self.driver.maximize_window()

    def set_proxy(self):
        self.driver.get(self.test_url)
        time.sleep(random.randint(2, 5))
        print(self.driver.page_source)
        cookies = self.driver.get_cookies()
        print(cookies)

    def close(self):
        time.sleep(5)
        self.driver.close()

if __name__ == '__main__':
    sp = SetProxyModel()
    sp.set_proxy()
    time.sleep(random.randint(3,5))
    sp.close()

运行结果如下:

 

 

本文标签: 无法访问seleniumip