Python爬蟲技術--基礎篇--內建模組itertools,contextlib和urllib
1.itertools
Python的內建模組itertools
提供了非常有用的用於操作迭代物件的函式。
首先,我們看看itertools
提供的幾個“無限”迭代器:
>>> import itertools
>>> natuals = itertools.count(1)
>>> for n in natuals:
... print(n)
...
1
2
3
...
因為count()
會建立一個無限的迭代器,所以上述程式碼會打印出自然數序列,根本停不下來,只能按Ctrl+C
退出。
cycle()
會把傳入的一個序列無限重複下去:
>>> import itertools
>>> cs = itertools.cycle('ABC') # 注意字串也是序列的一種
>>> for c in cs:
... print(c)
...
'A'
'B'
'C'
'A'
'B'
'C'
...
同樣停不下來。
repeat()
負責把一個元素無限重複下去,不過如果提供第二個引數就可以限定重複次數:
>>> ns = itertools.repeat('A', 3)
>>> for n in ns:
... print(n)
...
A
A
A
無限序列只有在for
迭代時才會無限地迭代下去,如果只是建立了一個迭代物件,它不會事先把無限個元素生成出來,事實上也不可能在記憶體中建立無限多個元素。
無限序列雖然可以無限迭代下去,但是通常我們會通過takewhile()
等函式根據條件判斷來截取出一個有限的序列:
>>> natuals = itertools.count(1)
>>> ns = itertools.takewhile(lambda x: x <= 10, natuals)
>>> list(ns)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
itertools
提供的幾個迭代器操作函式更加有用:
chain()
chain()
可以把一組迭代物件串聯起來,形成一個更大的迭代器:
>>> for c in itertools.chain('ABC', 'XYZ'):
... print(c)
# 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'
groupby()
groupby()
把迭代器中相鄰的重複元素挑出來放在一起:
>>> for key, group in itertools.groupby('AAABBBCCAAA'):
... print(key, list(group))
...
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']
實際上挑選規則是通過函式完成的,只要作用於函式的兩個元素返回的值相等,這兩個元素就被認為是在一組的,而函式返回值作為組的key。如果我們要忽略大小寫分組,就可以讓元素'A'
和'a'
都返回相同的key:
>>> for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()): ... print(key, list(group)) ... A ['A', 'a', 'a'] B ['B', 'B', 'b'] C ['c', 'C'] A ['A', 'A', 'a']
小結
itertools
模組提供的全部是處理迭代功能的函式,它們的返回值不是list,而是Iterator
,只有用for
迴圈迭代的時候才真正計算。
2.contextlib
在Python中,讀寫檔案這樣的資源要特別注意,必須在使用完畢後正確關閉它們。正確關閉檔案資源的一個方法是使用try...finally
:
try:
f = open('/path/to/file', 'r')
f.read()
finally:
if f:
f.close()
寫try...finally
非常繁瑣。Python的with
語句允許我們非常方便地使用資源,而不必擔心資源沒有關閉,所以上面的程式碼可以簡化為:
with open('/path/to/file', 'r') as f:
f.read()
並不是只有open()
函式返回的fp物件才能使用with
語句。實際上,任何物件,只要正確實現了上下文管理,就可以用於with
語句。
實現上下文管理是通過__enter__
和__exit__
這兩個方法實現的。例如,下面的class實現了這兩個方法:
class Query(object):
def __init__(self, name):
self.name = name
def __enter__(self):
print('Begin')
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
print('Error')
else:
print('End')
def query(self):
print('Query info about %s...' % self.name)
這樣我們就可以把自己寫的資源物件用於with
語句:
with Query('Bob') as q:
q.query()
@contextmanager
編寫__enter__
和__exit__
仍然很繁瑣,因此Python的標準庫contextlib
提供了更簡單的寫法,上面的程式碼可以改寫如下:
from contextlib import contextmanager
class Query(object):
def __init__(self, name):
self.name = name
def query(self):
print('Query info about %s...' % self.name)
@contextmanager
def create_query(name):
print('Begin')
q = Query(name)
yield q
print('End')
@contextmanager
這個decorator接受一個generator,用yield
語句把with ... as var
把變數輸出出去,然後,with
語句就可以正常地工作了:
with create_query('Bob') as q:
q.query()
很多時候,我們希望在某段程式碼執行前後自動執行特定程式碼,也可以用@contextmanager
實現。例如:
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("</%s>" % name)
with tag("h1"):
print("hello")
print("world")
上述程式碼執行結果為:
<h1>
hello
world
</h1>
程式碼的執行順序是:
with
語句首先執行yield
之前的語句,因此打印出<h1>
;yield
呼叫會執行with
語句內部的所有語句,因此打印出hello
和world
;- 最後執行
yield
之後的語句,打印出</h1>
。
因此,@contextmanager
讓我們通過編寫generator來簡化上下文管理。
@closing
如果一個物件沒有實現上下文,我們就不能把它用於with
語句。這個時候,可以用closing()
來把該物件變為上下文物件。例如,用with
語句使用urlopen()
:
from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('https://www.python.org')) as page:
for line in page:
print(line)
closing
也是一個經過@contextmanager裝飾的generator,這個generator編寫起來其實非常簡單:
@contextmanager
def closing(thing):
try:
yield thing
finally:
thing.close()
它的作用就是把任意物件變為上下文物件,並支援with
語句。
@contextlib
還有一些其他decorator,便於我們編寫更簡潔的程式碼。
3.urllib
urllib提供了一系列用於操作URL的功能。
Get
urllib的request
模組可以非常方便地抓取URL內容,也就是傳送一個GET請求到指定的頁面,然後返回HTTP的響應:
例如,對豆瓣的一個URLhttps://api.douban.com/v2/book/2129650
進行抓取,並返回響應:
from urllib import request
with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
data = f.read()
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', data.decode('utf-8'))
可以看到HTTP響應的頭和JSON資料:
Status: 200 OK
Server: nginx
Date: Tue, 26 May 2015 10:02:27 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2049
Connection: close
Expires: Sun, 1 Jan 2006 01:00:00 GMT
Pragma: no-cache
Cache-Control: must-revalidate, no-cache, private
X-DAE-Node: pidl1
Data: {"rating":{"max":10,"numRaters":16,"average":"7.4","min":0},"subtitle":"","author":["廖雪峰編著"],"pubdate":"2007-6",...}
如果我們要想模擬瀏覽器傳送GET請求,就需要使用Request
物件,通過往Request
物件新增HTTP頭,我們就可以把請求偽裝成瀏覽器。例如,模擬iPhone 6去請求豆瓣首頁:
from urllib import request
req = request.Request('http://www.douban.com/')
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
with request.urlopen(req) as f:
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', f.read().decode('utf-8'))
這樣豆瓣會返回適合iPhone的移動版網頁:
...
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="format-detection" content="telephone=no">
<link rel="apple-touch-icon" sizes="57x57" href="http://img4.douban.com/pics/cardkit/launcher/57.png" />
...
Post
如果要以POST傳送一個請求,只需要把引數data
以bytes形式傳入。
我們模擬一個微博登入,先讀取登入的郵箱和口令,然後按照weibo.cn的登入頁的格式以username=xxx&password=xxx
的編碼傳入:
from urllib import request, parse
print('Login to weibo.cn...')
email = input('Email: ')
passwd = input('Password: ')
login_data = parse.urlencode([
('username', email),
('password', passwd),
('entry', 'mweibo'),
('client_id', ''),
('savestate', '1'),
('ec', ''),
('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
])
req = request.Request('https://passport.weibo.cn/sso/login')
req.add_header('Origin', 'https://passport.weibo.cn')
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')
with request.urlopen(req, data=login_data.encode('utf-8')) as f:
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', f.read().decode('utf-8'))
如果登入成功,我們獲得的響應如下:
Status: 200 OK
Server: nginx/1.2.0
...
Set-Cookie: SSOLoginState=1432620126; path=/; domain=weibo.cn
...
Data: {"retcode":20000000,"msg":"","data":{...,"uid":"1658384301"}}
如果登入失敗,我們獲得的響應如下:
...
Data: {"retcode":50011015,"msg":"\u7528\u6237\u540d\u6216\u5bc6\u7801\u9519\u8bef","data":{"username":"[email protected]","errline":536}}
Handler
如果還需要更復雜的控制,比如通過一個Proxy去訪問網站,我們需要利用ProxyHandler
來處理,示例程式碼如下:
proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
with opener.open('http://www.example.com/login.html') as f:
pass
小結
urllib提供的功能就是利用程式去執行各種HTTP請求。如果要模擬瀏覽器完成特定功能,需要把請求偽裝成瀏覽器。偽裝的方法是先監控瀏覽器發出的請求,再根據瀏覽器的請求頭來偽裝,User-Agent
頭就是用來標識瀏覽器的。