鍍金池/ 問答/數(shù)據(jù)分析&挖掘  Python/ python3.x如何使用代理IP

python3.x如何使用代理IP

我調(diào)用我抓取的代理IP和請求頭進(jìn)行爬蟲,但是總是反饋失敗,我檢查了IP,發(fā)現(xiàn)也沒問題,到底如何正確使用
getRandomProxy()是調(diào)用隨機(jī)選擇一個代理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 數(shù)據(jù)失敗'%url)
        else:
            self.log.info(u'Python 返回URL:%s 數(shù)據(jù)成功'%url)
            return response.read()
回答
編輯回答
赱丅呿

當(dāng)你使用一個IP代理的時候請測試當(dāng)前IP是否能夠正常訪問
檢查 r.status_code 是否等于20X 如果是那么說明這個IP代理是能夠正常使用的

import requests

r = requests.get(url=url,proxies=proxies)
r.status_code 
2017年4月27日 12:14