1. 程式人生 > >python爬蟲系列(二):標準庫的使用(A)

python爬蟲系列(二):標準庫的使用(A)

(一)Py2和Py3中的基本庫使用的區分

Urllib庫是python中的一個功能強大的,用於操作URL。python2和python3中用法基本相同,但是。python2中分為urllib和urllib2庫。下面列出常見的變化有: 
1.python2.x使用import urllib2-->python3.x使用import urllib.request, urllib.error
2.python2.x使用import urllib -->python3.x使用import urllib.request, urllib.error,urllib.parse
3.python2.x使用import urlparse-->python3.x使用import urllib.parse
4.python2.x使用import urllib2.urlopen-->python3.x使用import urllib.request.urlopen
5.python2.x使用import urllib2.quote-->python3.x使用import urllib.request.quote
6.python2.x使用cookielib.CookieJar-->python3.x使用 http.CookieJar
7.python2.x使用import urllib2.Request-->python3.x使用import urllib.request.Request
大概也就這幾種常用到的模組。希望能認真的區分,這能讓你輕鬆面對兩個版本的python。

(二)通過實際程式碼來介紹各種模組的應用。

Ps:本人一直使用py3.5版本,所以如版本不同,請自行按照一中介紹的進行切換。

        小試牛刀:

import urllib.request
import urllib.parse
import http.cookiejar
url = "http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmint=yes&loginhash=L768q"
postdata = urllib.parse.urlencode({'usrname':'使用者名稱','password':'密碼'}).encode('utf-8')
req = urllib.request.Request(url,postdata)
req.add_header('User-Agent','Mozilla/5.0 (windows NT 6.1; WOW64) AppleWebkit/537.36')
cjar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cjar))
urllib.request.install_opener(opener)
file = opener.open(req)
print (file.read().decode('gbk'))

程式碼難點解析:這段程式碼雖然小,但卻涵蓋了常用到的爬蟲模組了。通過urllib.request傳送請求,把要登陸的使用者和密碼在通過urlencode的解析後構建post請求物件。
在這裡要強調–> 我們訪問的每一個網際網路頁面都是通過Http協議進行。而http 協議是一個無狀態協議。所謂的無狀態協議就是無法維持會話之間的狀態。為了保持會話的暢通,cookie和session應運而生。
所以,這裡的程式碼進行了cookie的物件的設定。即cjar = http.cookiejar.CookieJar()。然後自己建立了一個opener物件,攜帶cookier物件。

注:urlencode的作用:接受引數形式為:[(key1, value1), (key2, value2),…] 和 {‘key1’: ‘value1’, ‘key2’: ‘value2’,…}
返回的是形如key2=value2&key1=value1字串。
urllib.urlencode({‘name’: u’老王’.encode(‘utf8’), ‘sex’: u’男’.encode(‘utf8’)})
‘name=%E8%80%81%E7%8E%8B&sex=%E7%94%B7’

@關於cookie和session的使用,在接下來的系列中會詳細介紹。如果有什麼問題可以一起探討一下。