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()
运行结果如下:
版权声明:本文标题:selenium使用代理ip之后无法访问 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1727687419a1125493.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论