原教程來源於imooc
鏈接地址:http://www.imooc.com/learn/563
urllib的三種下載網頁方法
1、測試代碼
# urlopen的參數可以是request對象和url
from urllib import request
import http.cookiejar
url = 'http://www.baidu.com' # 指定url爲百度首頁
print('第一種方法:')
response1 = request.urlopen(url) # 用urllib.request的urlopen方法,以url作爲參數下載網頁
print(response1.getcode())
print(len(response1.read()))
print('第二種方法')
req = request.Request(url) # 創建request對象添加特殊處理,url作爲參數
req.add_header('user-agent', 'Mozilla/5.0') # 把爬蟲僞裝成瀏覽器
response2 = request.urlopen(req) # urlopen方法的參數改爲request
print(response2.getcode())
print(len(response2.read()))
print('第三種方法')
cj = http.cookiejar.CookieJar() # 創建cookie容器
opener = request.build_opener(request.HTTPCookieProcessor(cj)) # 創建opener,以cj爲容器
request.install_opener(opener) # 爲request安裝opener,使request具有cookie處理能力
response3 = request.urlopen(url)
print(response3.getcode())
print(cj) # 打印cookie容器內容
print(response3.read())
2、測試結果