名人名言数据练习
2018-07-04 本文已影响0人
李_佳兴
1、实验目的
名人名言数据练习,学习用scrapy框架编写爬虫代码采集数据。
2、实验过程
(1)、新建spider
进入想要存储爬虫代码的目录后,shift+鼠标右键打开命令行,输入scrapy startproject quotes,建立了一个爬虫项目,进入项目后,在spiders目录下新建python文件quotes.py,在此文件中编写爬虫代码。此时,项目结构为:

(2)、定义item

分析格言内容,需要获取四个字段,分别为内容(content),作者(author),关于作者(about)和标签(tags)。所以item.py文件为:

(3)、分析页面结构
打开http://quotes.toscrape.com/,按F12进入开发者模式,分析网页结构,发现格言列表为

,每一个类为quote的div标签包括一条格言。每一条格言的内容结构为:

格言的content的xpath为‘./span[@class="text"]’,author的xpath为‘.//small[@class="author"]’,about的xpath为‘.//a[contains(text(),"(about)")]’,tags的xpath为‘.//a[@class="tag"]’。
(4)、编写爬虫文件
每爬取完一页,进入下一页继续爬取,直到全部爬取完。
quotes.py代码如下:

3、爬取结果
在爬虫项目根目录下,打开命令行,输入scrapy crawl quotes -o quotes.json,爬取结果会保存在quotes.json文件里。部分爬取结果截图:

4、遇到的问题:
第一次爬取的结果双引号被转为\u201c,在settings.py中添加FEED_EXPORT_ENCODING = 'utf-8'后,输出正常。