官方文档:https://docs.python.org/3/library/urllib.htmlhtml
Py2.x:python
Urllib
库Urllin2
库Py3.x:缓存
Urllib
库变化:服务器
import urllib2
——-对应的,在Python3.x中会使用import urllib.request
,urllib.error
。import urllib
——-对应的,在Python3.x中会使用import urllib.request
,urllib.error
,urllib.parse
。import urlparse
——-对应的,在Python3.x中会使用import urllib.parse
。import urlopen
——-对应的,在Python3.x中会使用import urllib.request.urlopen
。import urlencode
——-对应的,在Python3.x中会使用import urllib.parse.urlencode
。import urllib.quote
——-对应的,在Python3.x中会使用import urllib.request.quote
。cookielib.CookieJar
——-对应的,在Python3.x中会使用http.CookieJar
。urllib2.Request
——-对应的,在Python3.x中会使用urllib.request.Request
。打开一个url的方法,返回一个文件对象,而后能够进行相似文件对象的操做cookie
1 import urllib.request 2 req = urllib.request.urlopen('http://www.baidu.com') 3 print(req.read())
read() , readline() , readlines() , fileno() , close() 函数
info():返回一个httplib.HTTPMessage 对象,表示远程服务器返回的头信息。编码
getcode():返回Http状态码,若是是http请求,200表示请求成功完成;404表示网址未找到。url
geturl():返回请求的url。spa
下载url定位到的html文件,不写路径filename则会被存为临时文件能够用 urllib.urlcleanup() 来清理缓存code
1 file_name = urllib.request.urlretrieve('http://www.baidu.com','%s/baidu.html'%BASE_DIR)
参数的解码和编码函数
1 import urllib.parse 2 dic = {'name':'melon','age':18} 3 data = urllib.parse.urlencode(dic) 4 5 print(data)
将urlstr解析成各个组件
1 import urllib.request 2 import urllib.parse 3 url = "http://www.baidu.com" 4 parsed = urllib.parse.urlparse(url) 5 print(parsed) 6 #输出:ParseResult(scheme='http', netloc='www.baidu.com', path='', params='', query='', fragment='')
将url的根域名和新url拼合成一个完整的url
1 import urllib.parse 2 url = "http://www.baidu.com" 3 new_path = urllib.parse.urljoin(url,"index.html") 4 print(new_path) 5 #输出:http://www.baidu.com/index.html
*******************************************************