Python3 爬蟲 使用代理 IP
阿新 • • 發佈:2019-01-07
寫了比較詳細的註釋,就不廢話了:
# -*- coding: utf-8 -*- #引入requests庫,沒有安裝 請 cmd> pip install requests import requests #要使用的代理 IP #我在西刺上找的,過期了的話自己找過 #西刺: https://www.xicidaili.com/ proxy = "119.101.112.15:9999" #設定代理 proxies = { 'http': 'http://' + proxy, #處理http連線的 'https': 'https://' + proxy, #處理https連線的 } #設定請求頭 User_Agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3" headers = {'User-Agent': User_Agent} try: #這段,設定自動關閉多餘連線,不然容易報 MaxRetryError s = requests.session() #獲取 會話 s.keep_alive = False #保持連線,設為 false s.adapters.DEFAULT_RETRIES = 300 #最大連線 改為300 #列印請求頭,代理資訊 print("headers",headers) print("proxies",proxies) #發起請求 response = s.get( #不用 s.get( 的話 可以直接用 requests.get( #你用瀏覽器直接訪問這個地址,可以看到你的IP "http://httpbin.org/get", proxies=proxies, headers=headers, timeout=5 ) #列印響應內容,結果有你代理IP的字樣就成功了 print(response.text) except requests.exceptions.ConnectionError as e: print('Error', e.args)
報錯 : 使用代理IP,遇到錯誤 [WinError 10061] 由於目標計算機積極拒
或者
報錯: Error (MaxRetryError("HTTPConnectionPool(host='119.101.112.9', port=9999): Max retries exceeded with url: 此處省略, 'Connection to 119.101.112.9 timed out. (connect timeout=5)'))"),)
請看: https://blog.csdn.net/weixin_42144379/article/details/85568234
上文解決方案已經使用,還是報此錯,點選 百度解決方案.
其他錯誤: 還是百度