剛開始學習python爬蟲,寫了一個簡單python程序爬取糗事百科。
具體步驟是這樣的:首先查看糗事百科的url:http://www.qiushibaike.com/8hr/page/2/?s=4959489,可以發現page后的數據代表第幾頁。
然后裝配request,注意要設置user_agent
代碼語言:JavaScript代碼運行次數:0運行復制
1 user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'2 headers = {'User-Agent': user_agent}3 request=urllib2.Request(url,headers=headers)4 response=urllib2.urlopen(request)
然后獲取返回的數據
代碼語言:javascript代碼運行次數:0運行復制
content=response.read().decode('utf-8')
然后是關鍵,使用正則匹配出所有的具體內容。這里可以使用瀏覽器的檢查功能查看頁面結構,寫出相對應的正則式,比如我們對下面的
…
進行匹配的正則式如下
立即學習“Python免費學習筆記(深入)”;
代碼語言:javascript代碼運行次數:0運行復制
pattern=re.compile('<div class="content">....<span>(.*?)</span>...</div>',re.S)
(.*?) ? :表示組,該部分為一個整體,將該部分匹配到字符串作為返回值返回,findall表示找到所有匹配的字符串,以序列的形式返回
參數re.S表示”.”點號匹配所有字符包括換行

下面是完整代碼
代碼語言:javascript代碼運行次數:0運行復制
1 import urllib 2 import urllib2 3 import re 4 import time 5 6 page=2 7 f=open("D:qiushi.txt","r+") 8 user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' 9 headers = {'User-Agent': user_agent}10 while page....<span>(.*?)</span>...',re.S)20 items=re.findall(pattern,content)21 f.write((url+"n").encode('utf-8'))22 for item in items:23 print "------"24 item=item+"n"25 print item26 f.write("------n".encode('utf-8'))27 f.write(item.replace('<br>','n').encode('utf-8'))28 except urllib2.URLError,e:29 if hasattr(e,"code"):30 print e.code31 if hasattr(e,"reason"):32 print e.reason33 finally:34 page+=135 time.sleep(1)
這里我是將找到的輸出到d盤下的qiushi.txt文件