scrapy抓取quote使用案例

来源:互联网 发布:云计算ai工程师 编辑:程序博客网 时间:2024/05/16 06:51

创建工程

scrapy  startproject scrapy_test 

目录结构

├── scrapy.cfg└── scrapy_test    ├── __init__.py    ├── items.py    ├── middlewares.py    ├── pipelines.py    ├── settings.py    └── spiders        ├── __init__.py        └── quotes.py主要文件的作用:scrapy.cfg :项目的配置文件scrapy_test/ :项目的Python模块,将会从这里引用代码scrapy_test/items.py :项目的目标文件(可以理解为model)scrapy_test/pipelines.py :项目的管道文件scrapy_test/settings.py :项目的设置文件scrapy_test/spiders/ :存储爬虫代码目录

创建爬虫

cd scrapy_testscrapy genspider [名字] [爬取网址]
爬虫文件变量和方法说明
  • name = “” :这个爬虫的识别名称,必须是唯一的,在不同的爬虫必须定义不同的名字
  • allow_domains = [] 是搜索的域名范围,也就是爬虫的约束区域,规定爬虫只爬取这个域名下的网页,不存在的URL会被忽略。
  • start_urls = () :爬取的URL元祖/列表。爬虫从这里开始抓取数据,所以,第一次下载的数据将会从这些urls开始。其他子URL将会从这些起始URL中继承性生成。
  • parse(self, response) :解析的方法,每个初始URL完成下载后将被调用,调用的时候传入从每一个URL传回的Response对象来作为唯一参数,主要作用如下:

负责解析返回的网页数据(response.body),提取结构化数据(生成item)
生成需要下一页的URL请求。

运行

scrapy crawl quotes

同时框架还提供了基于ipython的交互模式,通过 scrapy shell进入交互

scrapy shell [网址][s] Available Scrapy objects:[s]   scrapy     scrapy module (contains scrapy.Request, scrapy.Selector, etc)[s]   crawler    <scrapy.crawler.Crawler object at 0x104196978>[s]   item       {}[s]   request    <GET http://quotes.toscrape.com>[s]   response   <200 http://quotes.toscrape.com>[s]   settings   <scrapy.settings.Settings object at 0x1051968d0>[s]   spider     <QuotesSpider 'quotes' at 0x10543b198>[s] Useful shortcuts:[s]   fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)[s]   fetch(req)                  Fetch a scrapy.Request and update local objects [s]   shelp()           Shell help (print this help)[s]   view(response)    View response in a browserIn [1]: responseOut[1]: <200 http://quotes.toscrape.com>In [2]: response.textOut[2]: '<!DOCTYPE html>\n<html lang="en">\n<head>\n\t<meta charset="UTF-8">\n\t<title>Quotes to Scrape</title>\n    <link rel="stylesheet" href="/static/bootstrap.min.css">\n In [5]: response.css('.quote .text::text').extract()

保存结果

scrapy保存信息支持多种格式
'json', 'jsonlines', 'jl', 'csv', 'xml', 'marshal', 'pickle'
主要介绍四种

# json 格式 默认为Unicode编码scrapy crawl quotes -o quotes.json# jsonline 格式 默认为Unicode编码scrapy crawl quotes -o quotes.jsonl# csv 可用excel打开scrapy crawl quotes -o quotes.csv# xml scrapy crawl quotes -o quotes.xml# 将数据直接发送到服务器上scrapy crawl quotes -o ftp://user:pass@www.example.com/path/quotes.csv