1. 程式人生 > >Python爬蟲(十三)_案例:使用XPath的爬蟲

Python爬蟲(十三)_案例:使用XPath的爬蟲

本篇是使用XPath的案例,更多內容請參考:Python學習指南

案例:使用XPath的爬蟲

現在我們用XPath來做一個簡單的爬蟲,我們嘗試爬取某個貼吧裡的所有帖子且將該帖子裡每個樓層釋出的圖片下載到本地。

#-*- coding:utf-8 -*-
#tieba_xpath.py

"""
    作用:本案例使用XPath做一個簡單的爬蟲,我們嘗試爬去某個貼吧的所有帖子
"""

import os
import urllib2 import urllib from lxml import etree class Spider: def __init__(self): self.tiebaName = raw_input("請輸入需要訪問的貼吧: ") self.beginPage = int(raw_input("請輸入起始頁: ")) self.endPage = int(raw_input("請輸入終止頁: ")) self.url = "http://tieba.baidu.com/f" self.ua_header = {"User-Agent":"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1 Trident/5.0;"} #圖片編號 self.userName = 1 def tiebaSpider(self): for page in range(self.beginPage, self.endPage+1): pn = (page-1) * 50 #page number word = {'pn':pn, 'kw':self.tiebaName} word = urllib.urlencode(word) #轉換成url編碼格式(字串) myUrl = self.url + "?" + word #示例:http://tieba.baidu.com/f?kw=%E7%BE%8E%E5%A5%B3 & pn=50 #呼叫 頁面處理函式load_Page #並且獲取頁面所有帖子連結 links = self.loadPage(myUrl) #urllib2_test3.py #獲取頁面內容 def loadPage(self, url): req = urllib2.Request(url, headers = self.ua_header) html = urllib2.urlopen(req).read() #解析html為HTML DOM文件 selector = etree.HTML(html) #抓取當前頁面的所有帖子的url的後半部分,也就是帖子編號 #http://tieba.baidu.com/p/4884069807裡的"p/4884069807" links = selector.xpath('//div[@class="threadlist_lz clearfix"]/div/a[@rel="noreferrer"]/@href') #links型別為etreeElementString列表 #遍歷列表,並且合併為一個帖子地址,呼叫圖片處理函式loadImage for link in links: link = "http://tieba.baidu.com" + link self.loadImage(link) #獲取圖片 def loadImage(self, link): req = urllib2.Request(link, headers = self.ua_header) html = urllib2.urlopen(req).read() selector = etree.HTML(html) #獲取這個帖子裡面所有圖片的src路徑 imageLinks = selector.xpath('//img[@class="BDE_Image"]/@src') #依次取出圖片路徑,下載儲存 for imageLink in imageLinks: self.writeImages(imageLink) #儲存頁面內容 def writeImages(self, imageLink): """ 將images裡的二進位制內容存入到userName檔案中 """ print(imageLink) print "正在儲存檔案 %d..."%self.userName #1.開啟一個檔案,返回一個檔案物件 file = open('./images/'+str(self.userName) + '.png', 'wb') #獲取圖片裡內容 images = urllib2.urlopen(imageLink).read() #呼叫檔案物件write()方法,將page_html的內容寫入到檔案裡 file.write(images) #最後關閉檔案 file.close() #計數器自增1 self.userName += 1 #模擬__main__函式: if __name__ == '__main__': #首先建立爬蟲物件 mySpider = Spider() #呼叫爬蟲物件的方法,開始工作 mySpider.tiebaSpider()