python3.x如何使用代理IP

我调用我抓取的代理IP和请求头进行爬虫,但是总是反馈失败,我检查了IP,发现也没问题,到底如何正确使用
getRandomProxy()是调用随机选择一个代理ip

    def getRseponseContent(self,url):
        fakeHeaders = {'User-Agent': self.getRandomHeaders()}
        request = urllib.request.Request(url.encode('utf8'),headers = fakeHeaders)
        proxy = urllib.request.ProxyHandler({'http':'http://'  + self.getRandomProxy()})
        opener = urllib.request.build_opener(proxy)
        urllib.request.install_opener(opener)
        try:
            response = urllib.request.urlopen(request)
            time.sleep(1)
        except:
            self.log.error(u'Python 返回URL:%s 数据失败'%url)
        else:
            self.log.info(u'Python 返回URL:%s 数据成功'%url)
            return response.read()
阅读 4.1k
1 个回答

当你使用一个IP代理的时候请测试当前IP是否能够正常访问
检查 r.status_code 是否等于20X 如果是那么说明这个IP代理是能够正常使用的

import requests

r = requests.get(url=url,proxies=proxies)
r.status_code 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进