所謂網頁抓取,就是把URL地址中指定的網絡資源從網絡流中讀取出來,保存到本地。在Python中有很多庫可以用來抓取網頁,我們先學習urllib2
。
urllib2是Python2.x自帶的模塊(不需要下載,導入即可使用)
urllib2官網文檔:https://docs.python.org/2/library/urllib2.html
urllib2源碼
urllib2
在python3.x中被改為urllib.request
urlopen
我們先來段代碼:
#-*- coding:utf-8 -*- #01.urllib2_urlopen.py #導入urllib2庫 import urllib2 #向指定的url發送請求,並返回服務器的類文件對象 response = urllib2.urlopen("http://www.baidu.com") #類文件對象支持文件對象的操作方法,如read()方法讀取文件 html = response.read() #打印字符串 print(html)
執行寫好的python代碼,將打印結果:
python2 01.urllib2_urlopen.py
實際上,如果我們在瀏覽器打上百度主頁,右鍵選擇"查看源代碼",你會發現,跟我們剛才打印出來的是一模一樣的。也就是說,上面的4行代碼就已經幫我們把百度的首頁的全部代碼爬了下來。
一個基本的url請求對應的python代碼真的非常簡單。
Request
查看官方文檔url的用法如下:
urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]]) Open the URL url, which can be either a string or a Request object.
在我們第一個例子里,urlopen()的參數就是一個url地址;
但是如果需要執行更復雜的操作,比如增加http報頭,則必須創建一個Request實例來作為urlopen()的參數;而需要訪問的url地址則作為Request實例的參數。
#-*- coding:utf-8 -*- #02.urllib2_request.py import urllib2 #url作為Request()方法的參數,構造並返回一個Request對象 request = urllib2.Request("http://www.baidu.com") #Request對象作為一個urlopen()方法的參數,發送給服務器並接收響應 response = urllib2.urlopen(request) html = response.read() print(html)
運行結果是完全一樣的:
新建Request實例,除了必須要有url參數之外,還可以設置另外兩個參數:
- data(默認空):是伴隨url提交的數據(比如要post的數據),同時HTTP請求將從"GET"方式改為"POST"方式。
- headers(默認空):是一個字典,包含了需要發送的HTTP報頭的鍵值對。
這兩個參數下面會說到。
User-Agent
但是這樣直接用urllib2給一個網站發送請求的話,確實略有些唐突了,就好比,人家每家都有門,你以一個路人的身份直接闖進去顯然不是很禮貌。而且有一些站點不喜歡被程序(非人為訪問)訪問,有可能會拒絕你的訪問請求。
但是如果我們用一個合法的身份去請求別人網站,顯然人家就是歡迎的,所以我們就應該給我們的這個代碼加上一個身份,就是所謂的User-Agent
頭。
- 瀏覽器就是互聯網世界公認被允許的身份,如果我們希望我們的爬蟲程序更像一個真實用戶,那我們第一步,就是需要偽裝成一個被公認的瀏覽器。用不同的瀏覽器在發送請求的時候,會有不同的User-Agent頭。urllib2默認的User-Agent頭為:
Python-urllib/x.y
(x和y是Python主版本和次版本號,例如Python-urllib/2.7)
#-*- coding:utf-8 -*- #03.urllib2_useragent.py import urllib2 url = "http://www.itcast.cn" #IE 9.0的User-Agent,包含ua-header里 ua_header = {"User-Agent":"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;"} # url連同headers,一起構造Request請求,這個請求將附帶IE9.0瀏覽器的User-Agent request = urllib2.Request(url, headers = ua_header) #向服務器發送這個請求 response = urllib2.urlopen(request) html = response.read() print(html)
添加更多的Header信息
在HTTP Request中加入特定的Header,來構造一個完整的HTTP請求。
可以通過調用
Request.add_header()
添加/修改一個特定的header也可以通過調用Request.get_header()
來查看已有的header。
- 添加一個特定的header
#-*- coding:utf-8 -*- #04.urllib2_headers.py import urllib2 url = "http://www.itcast.cn" #IE 9.0的User-Agent header = {"User-Agent":"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;"} request =urllib2.Request(url, headers = header) #也可以通過調用Request.add_header()添加/修改一個特定的header request.add_header("Connection","keep-alive") #也可以通過調用Request.get_header()來查看header信息 request.get_header(header_name = "Connection") response = urllib2.urlopen(request) print(response.code) #可以查看響應狀態碼 html = response.read() print(html) 隨機添加/修改User-Agent #-*- coding:utf-8 -*- #05.urllib2_add_headers.py import urllib2 import random url = "http://www.itcast.cn" ua_list = [ "Mozilla/5.0 (Windows NT 6.1; ) Apple.... ", "Mozilla/5.0 (X11; CrOS i686 2268.111.0)... ", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X.... ", "Mozilla/5.0 (Macintosh; Intel Mac OS... " ] user_agent = random.choice(ua_list) request = urllib2.Request(url) #也可以通過調用Request.add_header()添加/修改一個特定的header request.add_header("User-Agent", user_agent) #第一個字母大寫,后面的全部小寫 request.add_header("User-agent") response = urllib2.urlopen(req) html = response.read() print(html)
注意
The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error