Python3学习笔记:使用代理访问url地址
生活随笔
收集整理的這篇文章主要介紹了
Python3学习笔记:使用代理访问url地址
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
#!?/usr/bin/env?python3 #?-*-?coding:utf-8?-*-'python進行代理的curl數據提交'__author__?=?'ken'import?os; import?sys;curPath?=?os.path.abspath(os.path.dirname(__file__)); sys.path.append(curPath);import?urllib.request; import?urllib.parse; import?socket;class?curl:def?__init__(self):pass;#?獲取用戶瀏覽器信息def?getUserAgent(self):userAgent?=?'Mozilla/5.0?(Windows?NT?6.1;?WOW64;?rv:39.0)?Gecko/20100101?Firefox/39.0';return?userAgent;#?進行數據提交def?run(self,?url,?param):self.url?=?url;self.param?=?param;self.userAgent?=?self.getUserAgent();self.proxyIpList?=?['117.135.196.197:55336',?'117.158.98.214:80',?'117.177.243.42:84',?'117.177.243.42:85'];data?=?urllib.parse.urlencode(self.param).encode(encoding='UTF8');req?=?urllib.request.Request(self.url,?data);req.add_header('User-Agent',?self.userAgent);for?proxyIp?in?self.proxyIpList:socket.setdefaulttimeout(3);??#?3秒未響應則為超時,跳過執行下一條try:#?添加代理proxy_handler?=?urllib.request.ProxyHandler({'http':?proxyIp});proxy_auth_handler?=?urllib.request.ProxyBasicAuthHandler();opener?=?urllib.request.build_opener(proxy_handler,?proxy_auth_handler);#?添加頭信息opener.addheaders?=?[('User-Agent',?self.userAgent)]#?數據請求response?=?opener.open(self.url,?data);#?獲取請求返還數據response_data?=?response.read().decode("utf8");print(proxyIp,?"正確:"?+?response_data);#?return?response_data;except?urllib.error.HTTPError?as?e:print(proxyIp,?"錯誤:錯誤代碼:",?e.code);#?print("錯誤內容:",?e.read().decode("utf8"));except?urllib.error.URLError?as?e:print(proxyIp,?'錯誤:未能獲取服務器信息.');#?print('錯誤原因:?',?e.reason);except:print(proxyIp,?"錯誤:其他未知錯誤!");#?cu?=?curl(); #?cu.run("www.test.com","{"key":123456789}");轉載于:https://my.oschina.net/kenblog/blog/486510
總結
以上是生活随笔為你收集整理的Python3学习笔记:使用代理访问url地址的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DIV周边添加投影及背景固定
- 下一篇: 一个资深投行女销售和低调IT创业男的故事