我调用我抓取的代理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()
当你使用一个IP代理的时候请测试当前IP是否能够正常访问
检查 r.status_code 是否等于20X 如果是那么说明这个IP代理是能够正常使用的