python代理ip连接失败_遇到问题--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
總結
以上是生活随笔為你收集整理的python代理ip连接失败_遇到问题--python--爬虫--使用代理ip第二次获取代理ip失败的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android os n9005,SM-
- 下一篇: 开发物体识别桌、_科研人员开发突破性的技