python 抓取網頁,python抓取
1. 主要內容
此部分的主要內容包括:
-
抓取網頁的的基本方法。
-
使用urllib和urllib2庫。
-
可以使用參數編碼。
2. 代碼舉例2.1 基本的抓取
使用sudo python命令,進入python環境。在此之前可以自己搭一個web伺服器,專門做測試用。我在我的一個Ubuntu系統中搭建了LNMP環境,地址為192.168.1.33。
其實python代碼很簡潔,抓取一個網頁只需要兩行代碼:
pyhon
import urllib
httpResponse = urllib.urlopen("http://192.168.1.33")
運行玩這兩行代碼後,可以通過httpResponse.code查看響應狀態,httpResponse.read()顯示返回的內容。
通過dir()函數可以進一步查看httpResponse內部的內容。
>>>
>>> dir(httpResponse)
[‘doc‘, ‘init‘, ‘iter‘, ‘module‘, ‘repr‘, ‘close’, ‘code’, ‘fileno’, ‘fp’, ‘getcode’, ‘geturl’, ‘headers’, ‘info’, ‘next’, ‘read’, ‘readline’, ‘readlines’, ‘url’]
>>>
>>> httpResponse.url
‘http://192.168.1.33’
>>> dir(httpResponse.headers)
[‘contains‘, ‘delitem‘, ‘doc‘, ‘getitem‘, ‘init‘, ‘iter‘, ‘len‘, ‘module‘, ‘setitem‘, ‘str‘, ‘addcontinue’, ‘addheader’, ‘dict’, ‘encodingheader’, ‘fp’, ‘get’, ‘getaddr’, ‘getaddrlist’, ‘getallmatchingheaders’, ‘getdate’, ‘getdate_tz’, ‘getencoding’, ‘getfirstmatchingheader’, ‘getheader’, ‘getheaders’, ‘getmaintype’, ‘getparam’, ‘getparamnames’, ‘getplist’, ‘getrawheader’, ‘getsubtype’, ‘gettype’, ‘has_key’, ‘headers’, ‘iscomment’, ‘isheader’, ‘islast’, ‘items’, ‘keys’, ‘maintype’, ‘parseplist’, ‘parsetype’, ‘plist’, ‘plisttext’, ‘readheaders’, ‘rewindbody’, ‘seekable’, ‘setdefault’, ‘startofbody’, ‘startofheaders’, ‘status’, ‘subtype’, ‘type’, ‘typeheader’, ‘unixfrom’, ‘values’]
>>> httpResponse.headers.items()
[(‘content-length’, ‘151’), (‘accept-ranges’, ‘bytes’), (‘server’, ‘nginx/1.1.19’), (‘last-modified’, ‘Mon, 04 Oct 2004 15:04:06 GMT’), (‘connection’, ‘close’), (‘date’, ‘Thu, 18 Jun 2015 12:30:19 GMT’), (‘content-type’, ‘text/html’)]
>>>
我們通過一段迴圈程式將httpResponse的頭部內容列印出來:
for header,value in httpResponse.headers.items(): print header + ' : ' + value
從Server欄位,我們可以看到伺服器端啟動並執行時Nginx,版本資訊為1.1.19。
2.2 帶參數URL請求
很多情況下,網頁是要和使用者互動的。即請求的路徑中會包含一些參數,例如使用者登入時會有使用者名稱和密碼,翻頁時會有頁面數,搜尋時會有關鍵詞等。而使用者的HTTP請求主要有兩種方式:POST和GET。現以GET為例說明一下,帶參數時url請求格式及文法。
為了測試方便,我寫了一個php小程式放在Nginx伺服器上。
<?php $output = "Hola!\n"; if (isset($_GET['testval']) && isset($_GET['teststr']) && is_numeric($_GET['testval'])) { for ($i = 0; $i < $_GET['testval']; ++$i) { $output .= $_GET['teststr'] . "\n"; } } echo $output; ?>
使用python做請求時,第一種方法和上面情況類似,只是URL的路徑尾碼上"?testval=3&teststr=hello"。另一種方法是參數單獨設定編碼,請求的時候再加上。先列出參數來args = {'testval':'3','teststr':'hello'},然後用urllib.urlencode()函數進行編碼。