1. 程式人生 > >python——爬蟲實現網頁資訊抓取

python——爬蟲實現網頁資訊抓取

首先實現關於網頁解析、讀取等操作我們要用到以下幾個模組

import urllib
import urllib2
import re

我們可以嘗試一下用readline方法讀某個網站,比如說百度

def test():
   f=urllib.urlopen('http://www.baidu.com')
   while True:
      firstLine=f.readline()
      print firstLine

下面我們說一下如何實現網頁資訊的抓取,比如說百度貼吧

我們大概要做幾件事情:

首先獲取網頁及其程式碼,這裡我們要實現多頁,即其網址會改變,我們傳遞一個頁數

   def getPage(self,pageNum):
          try:
               url=self.baseURL+self.seeLZ+'&pn='+str(pageNum)
               #建立request物件
               request=urllib2.Request(url)
               response=urllib2.urlopen(request)
               #print 'URL:'+url
               return response.read()
          except Exception,e:
               print e

之後我們要獲取小說內容,這裡咱們分為標題和正文。標題每頁都有,所以我們獲取一次就好了。

我們可以點選某網站,按f12檢視他的標題標籤是如何構造的,比如說百度貼吧是<title>…………

那我們就匹配reg=re.compile(r'<title>(.*?)。')來抓取這個資訊

標題抓取完我們要開始抓去正文了,我們知道正文會有很多段,所以我們要迴圈的去抓取整個items,這裡我們注意

對於文字的讀寫操作,一定要放在迴圈外。同時加入一些去除超連結、<br>等機制

最後,我們在主函式呼叫即可

完整程式碼:

# -*- coding:utf-8 -*-


import sys
reload(sys)
sys.setdefaultencoding('utf8')

#爬蟲之網頁資訊抓取
#需要的函式方法:urllib,re,urllib2

import urllib
import urllib2
import re

#測試函式->讀取
#def test():
#     f=urllib.urlopen('http://www.baidu.com')
#     while True:
#          firstLine=f.readline()
#          print firstLine



#針對於百度貼吧獲取前十頁樓主小說文字內容

class BDTB:
     def __init__(self,baseUrl,seeLZ):
          #成員變數
          self.baseURL=baseUrl
          self.seeLZ='?see_lz='+str(seeLZ)

     #獲取該頁帖子的程式碼
     def getPage(self,pageNum):
          try:
               url=self.baseURL+self.seeLZ+'&pn='+str(pageNum)
               #建立request物件
               request=urllib2.Request(url)
               response=urllib2.urlopen(request)
               #print 'URL:'+url
               return response.read()
          except Exception,e:
               print e
               
     #匹配標題
     def Title(self):
          html=self.getPage(1)
          #compile提高正則匹配效率
          reg=re.compile(r'<title>(.*?)。')
          #返回list列表
          items=re.findall(reg,html)
          f=open('output.txt','w+')
          item=('').join(items)
          f.write('\t\t\t\t\t'+item.encode('gbk'))
          f.close()

     #匹配正文
     def Text(self,pageNum):
          html=self.getPage(pageNum)
          #compile提高正則匹配效率
          reg=re.compile(r'"d_post_content j_d_post_content ">(.*?)</div>')
          #返回list列表
          items=re.findall(reg,html)
          f=open('output.txt','a+')
          #[1:]切片,第一個元素不需要,去掉。
          for i in items[1:]:
               #超連結去除
               removeAddr=re.compile('<a.*?>|</a>')
               #用""替換
               i=re.sub(removeAddr,"",i)
               #<br>去除
               i=i.replace('<br>','')              
               f.write('\n\n'+i.encode('gbk'))
          f.close()

               
#呼叫入口
baseURL='http://tieba.baidu.com/p/4638659116'
bdtb=BDTB(baseURL,1)
print '爬蟲正在啟動....'.encode('gbk')
#多頁
bdtb.Title()
print '抓取標題完畢!'.encode('gbk')
for i in range(1,11):
    print '正在抓取第%02d頁'.encode('gbk')%i
    bdtb.Text(i)
print '抓取正文完畢!'.encode('gbk')