python urllib的用法实例
生活随笔
收集整理的這篇文章主要介紹了
python urllib的用法实例
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
import?urllib2 import??urllib import??jsondef?_post_json_by_urllib(url,jsondata):request=urllib2.Request(url,jsondata)request.add_header("Content-type","application/json")request.get_method=lambda?:"POST"request=urllib2.urlopen(request)return?request.read()class?Api(object):def?__init__(self,url):self.url=urldef?get(self,data={}):#get請(qǐng)求assert?type(data)==dictdata=dict([((key?if?type(key)!=unicode?else?key.encode("utf-8"))?,\(v?if?type(v)!=unicode?else?v.encode("utf-8"))?)??for?key,v?in?data.items()])querystring=urllib.urlencode(data)if?"?"?not?in?self.url:url=self.url+"?"+querystringelse:url=self.url+'&'+querystringtry:fd=urllib2.urlopen(url)data=fd.read()return?(True,data)except?Exception?as?e?:return??(False,str(e))def?post(self,data={},is_json=False):#post請(qǐng)求assert?type(data)==dictdata=dict([((key?if?type(key)!=unicode?else?key.encode("utf-8"))?,\(v?if?type(v)!=unicode?else?v.encode("utf-8"))?)??for?key,v?in?data.items()])if?is_json==False:data=urllib.urlencode(data)try:#req?=?urllib2.Request(self.url,data)data=urllib2.urlopen(self.url,data,timeout=3)return?(True,data.read())except?Exception?as?e?:return??(False,str(e))else:try:data=json.dumps(data)result=_post_json_by_urllib(self.url,data)return??(True,result)except?Exception?as?e?:return??(False,str(e))轉(zhuǎn)載于:https://my.oschina.net/u/1458120/blog/666249
總結(jié)
以上是生活随笔為你收集整理的python urllib的用法实例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 领航商务之选——金立M5 plus体验札
- 下一篇: Nginx加入linux系统服务