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

情况

获取代理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
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

张小凡vip

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值