美文网首页我爱编程
Scrapy笔记-常用指令

Scrapy笔记-常用指令

作者: hhuua | 来源:发表于2018-06-21 13:34 被阅读0次

常用指令

创建项目

设置一个新的Scrapy项目。

scrapy startproject projectname

运行爬虫

scrapy crawl spidername

数据提取测试

scrapy shell 'hhttp://www.xxx.com'

css选择器

使用 shell,您可以尝试使用带有 response 对象的 CSS 选择元素:

>>> response.css('title')
[<Selector xpath='descendant-or-self::title' data='<title>Quotes to Scrape</title>'>]

要从上面的标题中提取文本,您可以:

>>> response.css('title::text').extract()
['Quotes to Scrape']

我们在CSS查询中添加了 ::text ,这意味着我们只想直接在 <title> 元素中选择文本元素。如果我们不指定 ::text ,我们将获得完整的 title 元素,包括其标签:

>>> response.css('title').extract()
['<title>Quotes to Scrape</title>']

可以使用 re 方法使用正则表达式进行提取:

>>> response.css('title::text').re(r'Quotes.*')
['Quotes to Scrape']
>>> response.css('title::text').re(r'Q\w+')
['Quotes']
>>> response.css('title::text').re(r'(\w+) to (\w+)')
['Quotes', 'Scrape']

Xpath

Scrapy 选择器还支持使用 XPath 表达式:

>>> response.xpath('//title')
[<Selector xpath='//title' data='<title>Quotes to Scrape</title>'>]
>>> response.xpath('//title/text()').extract_first()
'Quotes to Scrape'

数据存储

Feed

存储抓取数据的最简单方法是使用 Feed 导出(Feed exports)

scrapy crawl spidername -o xxxx.json

这将生成一个 quotes.json 文件,其中包含所有被抓取的项目,以 JSON 序列化。

使用其他格式,如JSON Lines

scrapy crawl spidername -o xxxx.jl

由于每条记录都是单独的行,因此您可以处理大文件,而无需将所有内容都放在内存中

爬虫参数

在运行爬虫时,可以使用 -a 选项为您的爬虫提供命令行参数:

scrapy crawl spidername -o xxxx-humor.json -a tag=xxx

这些参数传递给 Spider 的 __init__ 方法,默认成为spider属性。

您可以使用此方法使您的爬虫根据参数构建 URL来实现仅抓取带有特定tag的数据:

def start_requests(self):
        url = 'http://quotes.toscrape.com/'
        tag = getattr(self, 'tag', None)
        if tag is not None:
            url = url + 'tag/' + tag
        yield scrapy.Request(url, self.parse)

相关文章

  • Scrapy笔记-常用指令

    常用指令 创建项目 设置一个新的Scrapy项目。 运行爬虫 数据提取测试 css选择器 使用 shell,您可以...

  • Scrapy指令笔记

    fetch 可以直接获取一个网页genspider 创建爬虫文件runspider 运行一个爬虫settings ...

  • 《HEAD FIRST SQL》学习笔记,初学SQL

    SQL学习笔记&&常用指令 RDBMS(relational database management system...

  • python3.6安装scrapy框架

    网络爬虫,python3.6安装scrapy框架,cmd指令:pip install scrapy 由于Scrap...

  • Scrapy爬虫项目学习

    一、创建scrapy项目 1.安装scrapy环境 2.在指令目录创建scrapy工程 二、创建爬虫文件 Scra...

  • Scrapy笔记

    Scrapy笔记 安装scrapy框架: 安装scrapy:通过pip install scrapy即可安装。 如...

  • python网络爬虫笔记三

    一、Scrapy爬虫框架常用命令 二、scrapy使用 scrapy startproject demo 新建...

  • scrapy笔记

    1 scrapy的运行原理 参考:Learning Scrapy笔记(三)- Scrapy基础Scrapy爬虫入门...

  • ubuntu 常用指令笔记

    目录: 一.查看文件大小 二.查看当前文件系统各分区的大小 三.查看当前文件系统cpu,内存 四.查看当前文件系统...

  • Octave常用指令笔记

    Octave 版本号:4.2.1 四则: 逻辑运算 变量相关 在拥有GUI的Octave中,所有变量在左侧栏中有所...

网友评论

    本文标题:Scrapy笔记-常用指令

    本文链接:https://www.haomeiwen.com/subject/rsvqyftx.html