python爬取豆瓣網頁短評實戰!
阿新 • • 發佈:2019-02-13
首先我們開啟我的父親母親的網頁介面:連結(https://book.douban.com/subject/20389038/comments/),可以觀察到如下介面以及讀者對本書的評價:
接下來我們直接附上程式碼:
# 書名:我的父親母親 # 作者: [英] 多麗絲·萊辛 # 出版社: 南海出版公司 # 原作名: Alfred and Emily # 譯者: 匡詠梅 # 出版年: 2013-1 # 頁數: 238 # 定價: 29.50元 # 裝幀: 精裝 # 叢書: 新經典文庫·萊辛作品 # ISBN: 9787544263863 import requests from lxml import etree import pandas as pd #通過觀察的url翻頁的規律,使用for迴圈得到10個連結,儲存到urls列表中 urls=['https://book.douban.com/subject/20389038/comments/hot?p={}'.format(str(i)) for i in range(1, 11, 1)] comments = [] #初始化用於儲存短評的列表 for url in urls: #使用for迴圈分別獲取每個頁面的資料,儲存到comments列表 r = requests.get(url).text s = etree.HTML(r) file = s.xpath('//div[@class="comment"]/p/text()') comments = comments + file df = pd.DataFrame(comments) #把comments列表轉換為pandas DataFrame df.to_excel('190.xlsx') #使用pandas把資料儲存到excel表格
結果如下:
大家可以嘗試更換網址對其它書籍的爬取,多動手實踐,就可爬取更多公開的資料,並對其進行分析,不一樣的驚喜等著你,只要你可努力。