python代理ip连接失败_遇到问题--python--爬虫--使用代理ip第二次获取代理ip失败

本文详细描述了在Python爬虫中遇到的代理IP连接失败的问题,当第一次获取的代理IP失效,尝试再次获取时,发现使用的是失效的IP而非本机IP。问题的原因在于`urllib.request.install_opener(opener)`使得全局请求都使用了自定义代理。为解决此问题,建议仅在需要使用代理的特定方法中通过`opener.open()`发送请求,以避免影响其他无代理请求。
摘要由CSDN通过智能技术生成

情况

获取代理ip的代码

def ferch_proxy_ips():

try:

api = "http://dynamic.goubanjia.com/dynamic/get/12323.html?sep=3"

response = urllib.request.urlopen(api, timeout=8)

the_page = response.read()

content = the_page.decode("utf8")

print("获取代理ip" + content)

# 按照\n分割获取到的IP

ips = content.split('\n');

return ips

# 利用每一个IP

except Exception as e:

print(str("获取代理ip异常" + str(e)))

content = ""

return content

使用代理ip访问页面,使用代码如下:

def fetch_raw_respone_proxy(link,ipport):

proxy_support = urllib.request.ProxyHandler({'http': ipport})

opener = urllib.request.build_opener(proxy_support)

urllib.request.install_opener(opener)

print("使用代理ip"+ipport+"访问"+link)

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'

headers = {'User-Agent': user_agent}

f = urllib.request.Request(link, headers=headers)

response = f.urlopen(api, timeout=8)

# time.sleep(1)

return response

当第一次获取的代理ip失效时,重新去获取,发现连接失败,排查发现重新去获取IP使用的ip 是 第一次获取到的 已经失效的ip,而不是本机ip。

理论上 两个方法是独立的,一个使用了代理,一个没使用,应该不会有影响才对。

原因

urllib.request.install_opener(opener)

如果这么写,就是将opener应用到全局,之后所有的,不管是opener.open()还是urlopen() 发送请求,都将使用自定义代理。

解决方法

修改如下:

只使用opener.open()方法发送请求才使用自定义的代理,不影响到其他的方法,其他方法里urlopen()不使用自定义代理。

def fetch_raw_respone_proxy(link,ipport):

proxy_support = urllib.request.ProxyHandler({'http': ipport})

opener = urllib.request.build_opener(proxy_support)

# urllib.request.install_opener(opener)

print("使用代理ip"+ipport+"访问"+link)

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'

headers = {'User-Agent': user_agent}

f = urllib.request.Request(link, headers=headers)

response = opener.open(f, timeout=70)

# time.sleep(1)

return response

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值