欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python urllib的用法实例

发布时间:2025/5/22 python 161 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python urllib的用法实例 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

2019独角兽企业重金招聘Python工程师标准>>>

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请求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请求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))


转载于:https://my.oschina.net/u/1458120/blog/666249

总结

以上是生活随笔为你收集整理的python urllib的用法实例的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。