前言
爬取豆瓣網圖書TOP250的數據,書名、鏈接、作者、出版社、出版時間、價格、評分、評語,並將數據存儲於CSV文件中
本文爲整理代碼,梳理思路,驗證代碼有效性——2019.12.15
環境:
Python3(Anaconda3)
PyCharm
Chrome瀏覽器
主要模塊:
lxml
requests
csv
1.
爬取的豆瓣圖書首頁如下
2.
分析URL規律
https://book.douban.com/top250? # 首頁
https://book.douban.com/top250? start=25 # 第二頁
https://book.douban.com/top250? start=50 # 第三頁
https://book.douban.com/top250? start=75 # 第四頁
...
可以發現首頁的URL與其他的URL格式不一樣,但是通過測試發現可以通過URLhttps://book.douban.com/top250?start=0
來訪問首頁
我們用列表解析式來構造出相應的URL列表
urls = ['https://book.douban.com/top250?start={}'.format(str(i)) for i in range(0,250,25)]
3.
爬取書名、鏈接、作者、出版社、出版時間、價格、評分、評語等數據
分析源碼,進行解析
利用Xpath對其解析
# 所有信息均在tr class="item"中,先將該模塊提取出來方便進一步解析
infos = selector.xpath('//tr[@class="item"]')
for info in infos:
name = info.xpath('td/div/a/@title')[0] # 書名
url = info.xpath('td/div/a/@href')[0] # 鏈接
book_infos = info.xpath('td/p/text()')[0]
author = book_infos.split('/')[0] # 作者
publisher = book_infos.split('/')[-3] # 出版社
date = book_infos.split('/')[-2] # 出版時間
price = book_infos.split('/')[-1] # 價格
rate = info.xpath('td/div/span[2]/text()')[0] # 評分
comments = info.xpath('td/p/span/text()') # 評語
comment = comments[0] if len(comments) != 0 else "空"
3.
將數據存儲與CSV文件中
存儲過程比較簡單,“將大象裝進冰箱”三步
- “打開冰箱”
# 創建csv
fp = open('doubanbook.csv', 'wt', newline='', encoding='utf-8')
- “將大象裝進去”
# 寫入數據
writer.writerow((name, url, author, publisher, date, price, rate,comment))
- “關上冰箱”
# 關閉csv文件
fp.close()
至此,爬取豆瓣網圖書TOP250的數據就結束了
A.完整代碼
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 導入相應的庫文件
from lxml import etree
import requests
import csv
# 創建csv
fp = open('doubanbook.csv', 'wt', newline='', encoding='utf-8')
# 寫入header
writer = csv.writer(fp)
writer.writerow(('name', 'url', 'author', 'publisher', 'date', 'price', 'rate', 'comment'))
# 構造urls
urls = ['https://book.douban.com/top250? start={}'.format(str(i)) for i in range(0,250,25)]
# 加入請求頭
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36'
'(KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
for url in urls:
html = requests.get(url, headers=headers)
selector = etree.HTML(html.text)
# 取大標籤,以此循環
infos = selector.xpath('//tr[@class="item"]')
for info in infos:
name = info.xpath('td/div/a/@title')[0] # 書名
url = info.xpath('td/div/a/@href')[0] # 鏈接
book_infos = info.xpath('td/p/text()')[0]
author = book_infos.split('/')[0] # 作者
publisher = book_infos.split('/')[-3] # 出版社
date = book_infos.split('/')[-2] # 出版時間
price = book_infos.split('/')[-1] # 價格
rate = info.xpath('td/div/span[2]/text()')[0] # 評分
comments = info.xpath('td/p/span/text()') # 評語
comment = comments[0] if len(comments) != 0 else "空"
# 寫入數據
writer.writerow((name, url, author, publisher, date, price, rate,comment))
# 關閉csv文件
fp.close()