爬豆瓣读书Top250
摘要
本課題的主要目的是設計面向指定網站的網絡爬蟲程序,同時需要滿足不同的性能要求。
搜索引擎作為一個輔助人們檢索信息的工具。但是,這些通用性搜索引擎也存在著一定的局限性。不同領域、不同背景的用戶往往具有不同的檢索目的和需求,通過搜索引擎所返回的結果包含大量用戶不關心的網頁。為了解決這個問題,一個靈活的爬蟲有著無可替代的重要意義。
Python爬取豆瓣讀書Top250,可以自動分析構造的URL,實現對圖書前250名信息的爬取。
關鍵詞:python;爬蟲;
Abstract
The main purpose of this topic is to design a web crawler program for a designated website, and it needs to meet different performance requirements.
The search engine serves as a tool to assist people in retrieving information. However, these universal search engines also have certain limitations. Users in different fields and different backgrounds often have different retrieval purposes and needs. The results returned by the search engine contain a large number of web pages that users do not care about. In order to solve this problem, a flexible crawler has irreplaceable importance.
Python crawls Douban Reading Top250, which can automatically analyze the constructed URL to achieve crawling of the top 250 information in the book.
Keywords: python,spider;
目錄
1.引言 3
2. 系統結構 3
3. 實現代碼 3
3.1得到指定一個URL的網頁內容 4
模擬瀏覽器頭部信息,向豆瓣服務器發送消息 4
3.2爬取網頁 5
3.3.保存數據 7
把爬蟲獲取到的信息放入excel表格中 7
4. 實驗 7
5. 總結和展望 8
?
1.引言
?????互聯網由龐大的數據信息組成,將數據有效的檢索并組織呈現出來有著巨大的應用前景。搜索引擎作為一個輔助人們檢索信息的工具成為用戶訪問萬維網的入口和指南。但是,這些通用性搜索引擎也存在著一定的局限性。不同領域、不同背景的用戶往往具有不同的檢索目的和需求。比如你直接在百度上搜索最受歡迎的前250本書籍,可能你并不能找到符合自己要求的,因為通過搜索引擎所返回的結果包含大量用戶不關心的網頁。為了解決這個問題,一個靈活的爬蟲有著無可替代的重要意義。
2.系統結構
網絡爬蟲(又稱為網頁蜘蛛,網絡機器人,在FOAF社區中間,更經常的稱為網頁追逐者),是一種按照一定的規則,自動地抓取萬維網信息的程序或者腳本。另外一些不常使用的名字還有螞蟻、自動索引、模擬程序或者蠕蟲。
Python爬取豆瓣前250的圖書系統采用python爬蟲技術,用urllib.request模塊打開和讀取指定的URL,urllib.error模塊拋出異常;用re模塊匹配正則表達式,獲取我們想要爬取的網頁內容;用bs4中的BeautifulSoup模塊解析網頁,獲取數據;用xlwt模塊把我們爬取到的數據寫入excel表格中。
3.實現代碼
?
import urllib.request, urllib.error ?# 指定URL,獲取網頁數據
import re ?# 正則表達式,進行文字匹配
import xlwt ?# 進行excel操作
from bs4 import BeautifulSoup ?# 網頁解析,獲取數據
def main():
????baseurl = "https://book.douban.com/top250?start="
????# 1.爬取網頁
????datalist = getData(baseurl)
????savepath = ".\\豆瓣讀書Top250.xls"
????# 3.保存數據
????saveData(datalist, savepath)
# 圖書詳情鏈接的規則
findLink = re.compile(r'<a class="nbg" href="(.*?)"') ?# 創建正則表達式對象,表示規則(字符串模式)
# 圖書圖片
findImgSrc = re.compile(r'<img src="(.*?)"')
# 圖書的中文名
findTitle = re.compile(r'<a.*title="(.*)">')
# 圖書的外國名
findForeignName = re.compile(r'<span style="font-size:12px;">(.*)</span>')
# 圖書評分
findRating = re.compile(r'<span class="rating_nums">(.*)</span>')
# 評價人數
findJudge = re.compile(r'<span class="pl">[\s\D]*(\d*)人評價.*?</span>', re.S)#\s匹配任意空白字符,等價于 [\t\n\r\f].,\D匹配任意非數字# re.S使 . 匹配包括換行在內的所有字符
# 概況
findInq = re.compile(r'<span class="inq">(.*)</span>')
# 圖書的相關內容
findBd = re.compile(r'<p class="pl">(.*?)</p>')
3.1得到指定一個URL的網頁內容
?
模擬瀏覽器頭部信息,向豆瓣服務器發送消息
def askURL(url):
????????head = {
????????"User-Agent": "Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 73.0.3683.86 Safari / 537.36"
????}
????# 用戶代理,表示告訴豆瓣服務器,我們是什么類型的機器,瀏覽器(本質上是告訴瀏覽器,我們可以接受什么水平的)
????request = urllib.request.Request(url, headers=head)
????html = ""
????try:
????????response = urllib.request.urlopen(request)
????????html = response.read().decode("utf-8")
????????# print(html)
????except urllib.error.URLError as e:
????????if hasattr(e, "code"): ?# hasattr(object, name)判斷一個對象里面是否有name屬性或者name方法
????????????print(e.code)
????????if hasattr(e, "reason"):
????????????print(e.reason)
????return html
?
3.2爬取網頁
首先我們訪問“https://book.douban.com/top250”豆瓣圖書鏈接,可以知道每一頁有25條記錄,第一頁的鏈接“https://book.douban.com/top250?start=0”開始,后面每點擊下一頁start的值就+25,最后一頁的鏈接為“https://book.douban.com/top250?start=225”。因此我們可以用BeautifulSoup得到每一頁圖書的信息,再用正則表達式re匹配到我們需要的內容。
?
def getData(baseurl):
????datalist = []
????for i in range(0, 10): ?# 調用獲取頁面信息的函數,10次
????????url = baseurl + str(i * 25)
????????html = askURL(url) ?# 保存獲取到的網頁源碼
????????# .逐一解析數據
????????soup = BeautifulSoup(html, "html.parser")
????????for item in soup.find_all('table'):
????????????#print(item)
????????????data = [] ?# 保留一部電影的所有信息
????????????item = str(item)
????????????# 圖書詳情的鏈接
????????????link = re.findall(findLink, item)[0] ?# re庫用來通過正則表達式查找指定的字符串
????????????data.append(link) ?# 添加鏈接
????????????imgSrc = re.findall(findImgSrc, item)[0]
????????????data.append(imgSrc) ?# 添加圖片
????????????titles = re.findall(findTitle, item)[0]
????????????data.append(titles)
????????????foreignName = re.findall(findForeignName, item)
????????????if (len(foreignName) == 1):
????????????????name = re.sub(':', "", foreignName[0]).strip()
????????????????data.append(name)# 添加外國名
????????????else:
????????????????data.append(' ') ?# 外國名留空
????????????rating = re.findall(findRating, item)[0]
????????????data.append(rating) ?# 評分
????????????judgeNum = re.findall(findJudge, item)[0]
????????????#print("人數:%s結束" % judgeNum)
????????????data.append(judgeNum) ?# 添加評價人數
????????????inq = re.findall(findInq, item)
????????????if len(inq) != 0:
????????????????inq = inq[0].replace("。 ", "") ?# 去掉句號
????????????????data.append(inq) ?# 添加概述
????????????else:
????????????????data.append(" ") ?# 留空
????????????bd = re.findall(findBd, item)[0]
????????????# bd = re.sub('<br(\s+)?/>(\s+)?', " ", bd) ?# 去掉<br/>
????????????bd = re.sub('/', " ", bd) ?# 替換/
????????????bd = " ".join(bd.split())#默認為所有的空字符,包括空格、換行(\n)、制表符(\t)
????????????data.append(bd.strip()) ?# 去掉前后的空格strip() 方法用于移除字符串頭尾指定的字符(默認為空格或換行符)
????????????datalist.append(data) ?# 把處理好的一部電影信息存到datalist
????#print(datalist)
????return datalist
3.3.保存數據
把爬蟲獲取到的信息放入excel表格中
def saveData(datalist, savepath):
????book = xlwt.Workbook(encoding="utf-8", style_compression=0) ?# style_compression:表示是否壓縮
????sheet = book.add_sheet('豆瓣圖書Top250', cell_overwrite_ok=True) ?# 創建workbook對象,cell_overwrite_ok每次覆蓋
????col = ('圖書詳情鏈接', "圖書鏈接", "圖書中文名", "圖書外國名", "評分", "評價數", "概況", "相關信息")
????for i in range(0, 8):
????????sheet.write(0, i, col[i]) ?# 列名
????for i in range(0, 250):
????????print("第%d條" % (i + 1))
????????data = datalist[i]
????????for j in range(0, 8):
????????????sheet.write(i + 1, j, data[j])
????book.save(savepath)
if __name__ == "__main__": ?# 當程序執行時
????# 調用函數
????main()
????print("爬取完畢")
?
4.實驗
實驗結果:爬取到的圖書Top250存到excel表格
?
5.總結和展望
通過本次課程,學會了python爬蟲爬取靜態的html頁面,但是我還得多加學習,繼續探索爬蟲之路。當python的html頁面由js渲染時,該如何爬呢?值得我接下來繼續努力學習。
參考文獻:
[1] (美)米切爾(Mitchell,R.)著;陶俊杰,陳小莉譯. Python網絡數據采集[M]. 北京:人民郵電出版社,2016.
總結
以上是生活随笔為你收集整理的爬豆瓣读书Top250的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Unable to establish
- 下一篇: BREDR之inquiry及page