【20171226】urllib
python3中没有urllib2
python3 与 python2 关于 urllib的区别用法如下
python2 | python3 |
urllib.urlopen |
urllib.request.urlopen |
urllib.urlretrieve |
urllib.request.urlretrieve |
urllib.quote |
urllib.parse.quote |
1、urlopen
#coding=utf-8
# python3 用 urllib.request;python2用urllib import urllib.request ''' urlopen:打开一个url,返回一个文件对象 read() , readline() ,readlines() , fileno() , close() :这些方法的使用方式与文件对象完全一样 ''' htmlFile = urllib.request.urlopen('https://www.baidu.com/') # firstLine = htmlFile.readline() # print('获取第一行:',firstLine) # # lines = htmlFile.readlines() # print('逐行获取所有行:',lines) # all = htmlFile.read() # print('获取所有行:',all) # fileno = htmlFile.fileno() # print('文件描述:',fileno) # info = htmlFile.info() # print('远程服务器返回的头消息:',info) code = htmlFile.getcode() print('请求状态码:',code) url = htmlFile.geturl() print('请求的url:',url) htmlFile.close()
2、urlretrieve
#coding=utf-8 ''' urlretrieve:将url定位到html文件下载到本地 1)不指定filename,保存为临时文件 2)指定filename,存为本地文件 ''' import urllib.request # 临时文件 # filename = urllib.request.urlretrieve('https://www.baidu.com/') # # print(type(filename)) # # print(filename[0]) # print(filename[1]) # 本地文件 filename = urllib.request.urlretrieve('https://www.baidu.com/',filename='file/baidu.html') print(filename[0]) print(filename[1]) # 清除urlretrieve 产生的缓存 urllib.request.urlcleanup()
3、quote
#coding=utf-8 ''' quote(s,safe='/') s是字符串,对s进行编码,指定safe中的不编码,默认为/ quote_plus(s,safe='') s是字符串,对s进行编码,指定safe中的不编码,默认为空,但会将空格编码成+ ''' import urllib.parse # 编码 oQuote = urllib.parse.quote('https://www.baidu.com/') print('编码后的url:',oQuote) print(urllib.parse.quote(u'你+好/',safe='+')) oQuote_plus = urllib.parse.quote_plus('http://www.baidu.com') print(oQuote_plus) print(urllib.parse.quote_plus(u'你 好/',safe='/')) # 解码 print('解码:',urllib.parse.unquote('%E4%BD%A0+%E5%A5%BD%2F')) print('解码:',urllib.parse.unquote_plus('%E4%BD%A0+%E5%A5%BD%2F')) # +解码成空格
4、urlencode
#coding=utf-8 import urllib.parse import urllib.request # get请求 params = urllib.parse.urlencode({'spam':1,'eggs':2,'bacon':0}) print(params) # params此时是str response = urllib.request.urlopen('https://www.baidu.com?%s' %params) print('get请求url:',response.geturl()) # post请求 posturl = 'http://192.168.129.152:8090/queryRoadBookIdByRange.do' postdata = {'longitude':'118.9','latitude':'31.8','cityName':'南京市','roadCount':'3'} params = urllib.parse.urlencode(postdata) params = params.encode('utf-8') # 要将params encode成byte,post请求后面跟 byte print(params) response = urllib.request.urlopen(posturl,params) print('post响应:',response.read().decode('utf-8'))