在上一篇博客《python爬虫获取豆瓣电影TOP250》中,小菌为大家带来了如何将豆瓣电影Top250的数据存入MySQL数据库的方法。这次的分享,小菌决定再带着大家去研究如何爬取豆瓣图片的Top250信息,并将数据保存在csv文件中!
我们先根据网址https://book.douban.com/top250
来到豆瓣图书Top250的页面。。
同样,我们发现需要爬取10个网页的内容。
通过研究不同页数所对应url变化的规律,例如:
第二页的url为:https://book.douban.com/top250?start=25
第三页的url为:https://book.douban.com/top250?start=50
第十页(也就是最后一页)的url为:https://book.douban.com/top250?start=225
我们可以先构造出url:
# 构造urls
urls=['https://book.douban.com/top250?start={}'.format(i) for i in range(0,250,25)]
本次爬虫我们需要爬取的内容
更多的信息大家选中对应的元素右键"检查"查看数据分布情况!
接下来小菌直接上代码,较为准确的步骤说明在代码注释里了,各位小伙伴们自行"食用"!
"""
@File : 豆瓣图书Top250(手动).py
@Time : 2019/10/30 14:27
@Author : 封茗囧菌
@Software: PyCharm
转载请注明原作者
创作不易,仅供分享
"""
# 导入相关的库
from lxml import etree
import requests
import csv # 运用Python中的csv库,把爬取到的信息存储在本地的CSV文件中
# 新建一个csv文件
# Permission denied
# 重复使用同一个csv文件会出现[没有权限;拒绝访问]
fp=open('G:/Python/Crawler/doupanbooktest02.csv','wt',newline='',encoding='utf-8')
writer=csv.writer(fp)
# 写入表头信息
writer.writerow(('name','url','author','publisher','date','price','rate','comment'))
# 构造urls
urls=['https://book.douban.com/top250?start={}'.format(i) for i in range(0,250,25)]
# 加入请求头
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
}
for url in urls:
# 用requests库获取网页信息,lxml解析html文件
html=requests.get(url,headers=headers)
selector=etree.HTML(html.text)
# 取大标签,以此类推
# <tr class='item'>
infos=selector.xpath('//tr[@class="item"]')
for info in infos:
# IndexError: list index out of range
name = info.xpath('td/div/a/@title')[0]
url = info.xpath('td/div/a/@href')[0]
# /text 是获取到定位元素的文本值
book_infos = info.xpath('td/p/text()')[0]
# print(book_infos)
author = book_infos.split('/')[0]
publisher = book_infos.split('/')[-3]
date=book_infos.split('/')[-2]
price=book_infos.split('/')[-1]
rate=info.xpath('td[2]/div[2]/span[2]/text()')[0]
comments=info.xpath('td/p/span/text()')
comment=comments[0] if len(comments) !=0 else "空"
# 打印查看结果
print(name, url, author, publisher, date, price, rate, comment)
# 将上述的数据写入到csv文件
writer.writerow((name,url,author,publisher,date,price,rate,comment))
# 关闭csv文件
fp.close()
效果图:
doupanbooktest02.csv文件
本次的分享就到这里了,喜欢的小伙伴们记得点赞加关注~(更多关于python基础的内容小伙伴们移步至Python 基础|菜鸟教程)学习( • ̀ω•́ )✧