生活随笔
收集整理的這篇文章主要介紹了
Python爬虫(十一)_案例:使用XPath的爬虫
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
現(xiàn)在我們用XPath來(lái)做一個(gè)簡(jiǎn)單的爬蟲(chóng),我們嘗試爬取某個(gè)貼吧里的所有帖子且將該帖子里每個(gè)樓層發(fā)布的圖片下載到本地。
#-*- coding:utf-8 -*-
#tieba_xpath.py"""作用:本案例使用XPath做一個(gè)簡(jiǎn)單的爬蟲(chóng),我們嘗試爬去某個(gè)貼吧的所有帖子
"""import os
import urllib2
import urllib
from lxml
import etreeclass Spider:def __init__(self):self.tiebaName = raw_input(
"請(qǐng)輸入需要訪問(wèn)的貼吧: ")self.beginPage = int(raw_input(
"請(qǐng)輸入起始頁(yè): "))self.endPage = int(raw_input(
"請(qǐng)輸入終止頁(yè): "))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;"}#圖片編號(hào)self.userName = 1
def tiebaSpider(self):for page
in range(self.beginPage, self.endPage+1
):pn = (page-1) * 50
#page numberword = {
'pn':pn,
'kw':self.tiebaName}word = urllib.urlencode(word)
#轉(zhuǎn)換成url編碼格式(字符串)myUrl = self.url +
"?" +
word#示例:http://tieba.baidu.com/f?kw=%E7%BE%8E%E5%A5%B3 & pn=50#調(diào)用 頁(yè)面處理函數(shù)load_Page#并且獲取頁(yè)面所有帖子鏈接links = self.loadPage(myUrl)
#urllib2_test3.py#獲取頁(yè)面內(nèi)容def loadPage(self, url):req = urllib2.Request(url, headers =
self.ua_header)html =
urllib2.urlopen(req).read()#解析html為HTML DOM文檔selector =
etree.HTML(html)#抓取當(dāng)前頁(yè)面的所有帖子的url的后半部分,也就是帖子編號(hào)#http://tieba.baidu.com/p/4884069807里的"p/4884069807"links = selector.xpath(
'//div[@class="threadlist_lz clearfix"]/div/a[@rel="noreferrer"]/@href')#links類型為etreeElementString列表#遍歷列表,并且合并為一個(gè)帖子地址,調(diào)用圖片處理函數(shù)loadImagefor link
in links:link =
"http://tieba.baidu.com" +
linkself.loadImage(link)#獲取圖片def loadImage(self, link):req = urllib2.Request(link, headers =
self.ua_header)html =
urllib2.urlopen(req).read()selector =
etree.HTML(html)#獲取這個(gè)帖子里面所有圖片的src路徑imageLinks = selector.xpath(
'//img[@class="BDE_Image"]/@src')#依次取出圖片路徑,下載保存for imageLink
in imageLinks:self.writeImages(imageLink)#保存頁(yè)面內(nèi)容def writeImages(self, imageLink):"""將images里的二進(jìn)制內(nèi)容存入到userName文件中"""print(imageLink)print "正在存儲(chǔ)文件 %d..."%
self.userName#1.打開(kāi)一個(gè)文件,返回一個(gè)文件對(duì)象file = open(
'./images/'+str(self.userName) +
'.png',
'wb')#獲取圖片里內(nèi)容images =
urllib2.urlopen(imageLink).read()#調(diào)用文件對(duì)象write()方法,將page_html的內(nèi)容寫(xiě)入到文件里
file.write(images)#最后關(guān)閉文件
file.close()#計(jì)數(shù)器自增1self.userName += 1
#模擬__main__函數(shù):
if __name__ ==
'__main__':#首先創(chuàng)建爬蟲(chóng)對(duì)象mySpider =
Spider()#調(diào)用爬蟲(chóng)對(duì)象的方法,開(kāi)始工作mySpider.tiebaSpider()
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/moying-wq/p/11569992.html
總結(jié)
以上是生活随笔為你收集整理的Python爬虫(十一)_案例:使用XPath的爬虫的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。