该文本是听过崔庆才老师讲解之后做的笔记。urllib有以下几个大的功能:
目录
urllib.request
import urllib.request
import urllib.parse
#response = urllib.request.urlopen('http://www.baidu.com')
#print(response.read().decode('utf8'))
这是最简单的爬取代码,response返回的是byte型的,需要解码为unicode。
import socket
import urllib.request
import urllib.error
try:
response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
except urllib.error.URLError as e:
if isinstance(e.reason, socket.timeout):
print('TIME OUT')
这个主要是来看timeout,如果在0.1秒内没有返回任何结果,则返回错误。
import urllib.request
response = urllib.request.urlopen('https://www.python.org')
print(type(response))
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))
'''<class 'http.client.HTTPResponse'>
200
[('Server', 'nginx'), ('Content-Type', 'text/html; charset=utf-8'),
('X-Frame-Options', 'SAMEORIGIN'), ('x-xss-protection', '1; mode=block'),
('X-Clacks-Overhead', 'GNU Terry Pratchett'), ('Via', '1.1 varnish'),
('Content-Length', '50069'), ('Accept-Ranges', 'bytes'),
('Date', 'Tue, 27 Nov 2018 13:35:20 GMT'), ('Via', '1.1 varnish'),
('Age', '2976'), ('Connection', 'close'),
('X-Served-By', 'cache-iad2143-IAD, cache-tyo19932-TYO'),
('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '1, 3412'),
('X-Timer', 'S1543325721.735388,VS0,VE0'), ('Vary', 'Cookie'),
('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]
nginx'''
response有几个属性,如上图所示。
from urllib import request, parse
url = 'http://httpbin.org/post'
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Host': 'httpbin.org'
}
dict = {
'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, headers=headers, method='POST')
print(req)
response = request.urlopen(req)
print(response.read().decode('utf-8'))
'''<urllib.request.Request object at 0x000002E31B1E2588>
{
"args": {},
"data": "",
"files": {},
"form": {
"name": "Germey"
},
"headers": {
"Accept-Encoding": "identity",
"Connection": "close",
"Content-Length": "11",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"
},
"json": null,
"origin": "106.47.92.40",
"url": "http://httpbin.org/post"
}
'''
这个涉及到了request的使用,在下一张会详解,记住就可以了。
urllib.parse
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result)
'''<class 'urllib.parse.ParseResult'>
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')'''
urlparse解析将一段url解析为几段。
from urllib.parse import urlunparse
data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data))
'''http://www.baidu.com/index.html;user?a=6#comment'''
这个是urlunparse,将一对零散的组合成一个完整的url。
from urllib.parse import urlparse
result = urlparse('mp.csdn.net/postedit/84573678', scheme='https')
print(result)
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments=False)
print(result)
'''ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5#comment', fragment='')'''
from urllib.parse import urljoin
print(urljoin('http://www.baidu.com', 'FAQ.html'))
print(urljoin('http://www.baidu.com', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html?question=2'))
print(urljoin('http://www.baidu.com?wd=abc', 'https://cuiqingcai.com/index.php'))
print(urljoin('http://www.baidu.com', '?category=2#comment'))
print(urljoin('www.baidu.com', '?category=2#comment'))
print(urljoin('www.baidu.com#comment', '?category=2'))
'''http://www.baidu.com/FAQ.html
https://cuiqingcai.com/FAQ.html
https://cuiqingcai.com/FAQ.html
https://cuiqingcai.com/FAQ.html?question=2
https://cuiqingcai.com/index.php
http://www.baidu.com?category=2#comment
www.baidu.com?category=2#comment
www.baidu.com?category=2'''
还有一个urljoin的用法,不过我现在觉得没有什么大的用处哈。
from urllib.parse import urlencode
params = {
'name': 'germey',
'age': 22
}
base_url = 'http://www.baidu.com?'
url = base_url + urlencode(params)
print(url)
'''http://www.baidu.com?name=germey&age=22'''
这个的用法倒是比较常见。
urllib.error
from urllib import request, error
try:
response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
print(e.reason)
else:
print('Request Successfully')
'''Not Found
404
Server: nginx/1.10.3 (Ubuntu)
Date: Tue, 27 Nov 2018 13:56:49 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
Vary: Cookie
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Link: <https://cuiqingcai.com/wp-json/>; rel="https://api.w.org/"'''
error有几种属性的错误,常用的有HTTPError和URLError。
urllib.robotparser
urllib.cookie
import http.cookiejar, urllib.request
cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('https://blog.csdn.net/')
for item in cookie:
print(item.name+"="+item.value)
'''dc_session_id=10_1543327921521.346928
uuid_tt_dd=8793671149615679850_20181127
'''
这个可以当成一个模板使用,用来获取cookie的一些属性。
import http.cookiejar, urllib.request
filename = "cookie.txt"
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)
这个用来将获取的cookie属性保存在一个文件中,不过保存的格式是按照MozillarCookieJar来保存的。
import http.cookiejar, urllib.request
filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)
import http.cookiejar, urllib.request
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))
这两个是配套来使用,可以保存会话的长时间存在。注意这个是以LWPCookieJar的格式来保存的。