Pytho2:
- Urllib庫
- Urllib2庫
Python3:
- Urllib庫
變化:
- 在Pytho2.x中使用import urllib2——-對應的,在Python3.x中會使用import urllib.request饵逐,urllib.error。
- 在Pytho2.x中使用import urllib——-對應的菱阵,在Python3.x中會使用import urllib.request,urllib.error,urllib.parse宏蛉。
- 在Pytho2.x中使用import urlparse——-對應的儿咱,在Python3.x中會使用import urllib.parse庭砍。
- 在Pytho2.x中使用import urlopen——-對應的,在Python3.x中會使用import urllib.request.urlopen混埠。
- 在Pytho2.x中使用import urlencode——-對應的怠缸,在Python3.x中會使用import urllib.parse.urlencode。
- 在Pytho2.x中使用import urllib.quote——-對應的钳宪,在Python3.x中會使用import urllib.request.quote揭北。
- 在Pytho2.x中使用cookielib.CookieJar——-對應的,在Python3.x中會使用http.CookieJar吏颖。
- 在Pytho2.x中使用urllib2.Request——-對應的搔体,在Python3.x中會使用urllib.request.Request。
最簡單的爬蟲程序
import urllib.request
file=urllib.request.urlopen('http://www.baidu.com')
data=file.read() #讀取全部
fhandle=open("./1.html","wb") #將爬取的網(wǎng)頁保存在本地
fhandle.write(data)
fhandle.close()
模擬瀏覽器行為
import urllib.request
import urllib.parse
url = 'http://www.baidu.com'
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36'
}
request = urllib.request.Request(url, headers=header)
reponse = urllib.request.urlopen(request).read()
fhandle = open("./baidu.html", "wb")
fhandle.write(reponse)
fhandle.close()
代理IP的使用
import urllib.request
def use_proxy(proxy_addr,url):
proxy=urllib.request.ProxyHandler({'http':proxy_addr})
opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)
urllib.request.install_opener(opener)
data=urllib.request.urlopen(url).read().decode('utf8')
return data
proxy_addr='61.163.39.70:9999'
data=use_proxy(proxy_addr,'http://www.baidu.com')
print(len(data))
cookielib庫和HTTPCookieProcessor處理器
Python處理Cookie半醉,一般是通過cookielib模塊和urllib的request模塊的HTTPCookieProcessor處理器類一起使用
- cookielib模塊:主要作用是提供用于存儲cookie的對象
- HTTPCookieProcessor處理器:只要處理cookies對象疚俱,并構建handler對象
cookielib庫
該模塊主要的對象有CookieJar、FileCookieJar缩多、MozillaCookieJar呆奕、LWPCookieJar
- CookieJar:管理HTTP cookie值、存儲HTTP請求生成的cookie衬吆、向傳出的HTTP請求添加cookie的對象梁钾。整個 cookie 都存儲在內存中。
- FileCookieJar (filename,delayload=None,policy=None):CookieJar 派生而來逊抡,將 cookie 存儲到文件中陈轿。filename 是存儲 cookie 的文件名。delayload 為 True 時支持延遲訪問文件,即只有在需要時才讀取文件或在文件中存儲數(shù)據(jù)麦射。
- MozillaCookieJar (filename,delayload=None,policy=None) : 從 FileCookieJar 派 生 而 來 蛾娶,MozillaCookieJar 實例與 Mozilla 瀏覽器 cookies.txt 兼容。
- LWPCookieJar (filename,delayload=None,policy=None):從 FileCookieJar 派生而來潜秋,實例與
libwww-perl 標準的 Set-Cookie3 文件格式兼容蛔琅。 - HTTPCookieProcessor 處理器:處理 cookie 對象,并構建 handler 處理器對象峻呛。
COOKIES的使用
import urllib.request
import urllib.parse
import urllib.error
import http.cookiejar
url='http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=La2A2'
data={
'username':'zhanghao',
'password':'mima',
}
postdata=urllib.parse.urlencode(data).encode('utf8')
header={
'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
request=urllib.request.Request(url,postdata,headers=header)
#使用http.cookiejar.CookieJar()創(chuàng)建CookieJar對象
cjar=http.cookiejar.CookieJar()
#使用HTTPCookieProcessor創(chuàng)建cookie處理器罗售,并以其為參數(shù)構建opener對象
cookie=urllib.request.HTTPCookieProcessor(cjar)
opener=urllib.request.build_opener(cookie)
#將opener安裝為全局
urllib.request.install_opener(opener)
try:
reponse=urllib.request.urlopen(request)
except urllib.error.HTTPError as e:
print(e.code)
print(e.reason)
fhandle=open('./test1.html','wb')
fhandle.write(reponse.read())
fhandle.close()
url2='http://bbs.chinaunix.net/forum-327-1.html' #打開test2.html文件,會發(fā)現(xiàn)此時會保持我們的登錄信息钩述,為已登錄狀態(tài)寨躁。也就是說,對應的登錄狀態(tài)已經通過Cookie保存牙勘。
reponse2=urllib.request.urlopen(url)
fhandle2=open('./test2.html','wb')
fhandle2.write(reponse2.read())
fhandle2.close()