python網(wǎng)絡(luò)爬蟲–簡(jiǎn)單爬取糗事百科

剛開始學(xué)習(xí)python爬蟲,寫了一個(gè)簡(jiǎn)單python程序爬取糗事百科。

具體步驟是這樣的:首先查看糗事百科的url:http://www.qiushibaike.com/8hr/page/2/?s=4959489,可以發(fā)現(xiàn)page后的數(shù)據(jù)代表第幾頁(yè)。

然后裝配request,注意要設(shè)置user_agent

代碼語言:JavaScript代碼運(yùn)行次數(shù):0運(yùn)行復(fù)制

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)

然后獲取返回的數(shù)據(jù)

代碼語言:javascript代碼運(yùn)行次數(shù):0運(yùn)行復(fù)制

content=response.read().decode('utf-8')

然后是關(guān)鍵,使用正則匹配出所有的具體內(nèi)容。這里可以使用瀏覽器的檢查功能查看頁(yè)面結(jié)構(gòu),寫出相對(duì)應(yīng)的正則式,比如我們對(duì)下面的

進(jìn)行匹配的正則式如下

立即學(xué)習(xí)Python免費(fèi)學(xué)習(xí)筆記(深入)”;

代碼語言:javascript代碼運(yùn)行次數(shù):0運(yùn)行復(fù)制

pattern=re.compile('<div class="content">....<span>(.*?)</span>...</div>',re.S)

(.*?) ? :表示組,該部分為一個(gè)整體,將該部分匹配到字符串作為返回值返回,findall表示找到所有匹配的字符串,以序列的形式返回

參數(shù)re.S表示”.”點(diǎn)號(hào)匹配所有字符包括換行

python網(wǎng)絡(luò)爬蟲–簡(jiǎn)單爬取糗事百科

下面是完整代碼

代碼語言:javascript代碼運(yùn)行次數(shù):0運(yùn)行復(fù)制

 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文件

以上就是<a

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊6 分享