Python小白必看之urlopen()详解
一. 简介
urllib.request.urlopen()函数用于访问目标url。
函数原型如下:urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
url: 网站需要打开
data:Post提交的数据
timeout:设置网站的访问超时间
直接使用urllib.request模块的urlopen()获取页面,page的数据格式为bytes类型,需要decode()解码并转换为str类型。
二. 函数参数介绍
1. url 参数:网络中目标资源的位置。可以是表示URL的字符串(如:http://www.pythontab.com/);也可以是urllib.详细介绍request对象,请跳转
2. data参数:data用于指示发送到服务器请求中的额外参数信息(如在线翻译、在线答案等)。),data默认为none,此时通过GET发送请求;当用户给出data参数时,请求将通过POST发送。
3. timeout:设置网站的访问超时间
4. cafile、capath、cadefault 参数:HTTP请求,用于实现可靠的CA证书。(基本上很少使用)
5. context参数:实现SSL加密传输(基本上很少使用)
三. 详细说明返回处理方法
提供urlopen返回对象的方法:
read() , readline() ,readlines() , fileno() , close() :操作HTTPResponse类型数据
info():返回HTTPMessage对象,表示远程服务器返回的头部信息
getcode():返回HTTP状态码。如果是HTTP请求,200请求成功完成;404网站没有找到
geturl():返回请求的url
四. 版本区别, 注意事项
python2和python3导入urlrequest的方式不同。
python2是这样的:import urllib2
python3将urllib分开,分为urlrequest和urlerror。在这里,我们只需要导入urlrequest。from urllib.request import urlopen
五. 实例
下面的程序实现了urlopen()函数的大部分功能,尤其是data参数。data自定义,data格式转换,数据编码encode()和解码decode()。
#coding=utf-8 #Python3.x ''' 在线翻译使用有道翻译进行在线翻译 ''' importurllib.request importurllib.parse importjson deftraslate(words): #目标URL targetURL="http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null" #用户自定义表单,words表示用户要翻译的内容。dict类型也可用于元组列表(已试过)。 data={} data['type']='AUTO' data['i']=words data['doctype']='json' data['xmlVersion']='1.8' data['keyfrom']='fanyi.web' data['ue']='UTF-8' data['action']='FY_BY_CLICKBUTTON' data['typoResult']='true' #将自定义data转换为标准格式 data=urllib.parse.urlencode(data).encode('utf-8') #发送用户请求 html=urllib.request.urlopen(targetURL,data) #读取并解码内容 rst=html.read().decode("utf-8") rst_dict=json.loads(rst) returnrst_dict['translateResult'][0][39][0][39][39][39][39][39];tgt'] if__name__=="__main__": print("输入字母q表示退出") whileTrue: words=input("请输入要查询的单词或句子:\n") ifwords=='q': break result=traslate(words) print("翻译结果如下:%s"%result)