python爬虫获取豆瓣图书Top250

        在上一篇博客《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 基础|菜鸟教程)学习( • ̀ω•́ )✧

评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大数据梦想家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值