爬虫练习

编程入门 行业动态 更新时间:2024-10-25 22:25:08

<a href=https://www.elefans.com/category/jswz/34/1770264.html style=爬虫练习"/>

爬虫练习

前言

爬取豆瓣网图书TOP250的数据,书名、链接、作者、出版社、出版时间、价格、评分、评语,并将数据存储于CSV文件中

本文为整理代码,梳理思路,验证代码有效性——2019.12.15


环境:
Python3(Anaconda3)
PyCharm
Chrome浏览器

主要模块:
lxml
requests
csv

1.

爬取的豆瓣图书首页如下

2.

分析URL规律

?  # 首页
? start=25  # 第二页
? start=50  # 第三页
? start=75  # 第四页
...

可以发现首页的URL与其他的URL格式不一样,但是通过测试发现可以通过URL=0来访问首页
我们用列表解析式来构造出相应的URL列表

urls = ['={}'.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文件中
存储过程比较简单,“将大象装进冰箱”三步

  1. “打开冰箱”
# 创建csv
fp = open('doubanbook.csv', 'wt', newline='', encoding='utf-8')
  1. “将大象装进去”
# 写入数据
writer.writerow((name, url, author, publisher, date, price, rate,comment))
  1. “关上冰箱”
# 关闭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 = ['? 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()

更多推荐

爬虫练习

本文发布于:2024-02-13 00:32:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1690013.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:爬虫

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!