1. Pause and resume a crawl

Scrapy supports this functionality out of the box by providing > the following facilities:

  • a scheduler that persists scheduled > >requests on disk

  • a duplicates filter that persists >visited requests on disk

  • an extension that keeps some spider state (key/value pairs) > persistent between > batches

run a crawl by

scrapy crawl somespider -s JOBDIR=crawls/somespider_dir

use Ctrl+C to close a drawl and resume by the same command above

2. 发起一次get请求

e.g.

页面A是新闻的列表,包含了每个新闻的链接

要发起一个请求去获取新闻的内容

通过设置request.meta,可以将参数带到callback函数中去,用response.meta接收

def parse(self, response):
newslist = response.xpath('//ul[@class="linkNews"]/li') for item in newslist:
news = News()
news['title'] = item.xpath('a/text()').extract_first(default = '') contentUri = item.xpath('a/@href').extract_first(default = '')
request = scrapy.Request(contentUri,
callback = self.getContent_callback,
headers = headers)
request.meta['item'] = news
yield request def getContent_callback(self, response):
news = response.meta['item']
item['content'] = response.xpath('//article[@class="art_box"]').xpath('string(.)').extract_first(default = '').strip()
yield item

3. 交互式shell

可以在这里交互式地获取各种信息,如response.status

我主要用来调试xpath(!shell中调试结果并不可靠)

PS C:\Users\patrick\Documents\Visual Studio 2017\Projects\ScrapyProjects> scrapy shell --nolog 'http://mil.news.sina.com.cn/2011-03-31/1342640379.html'
[s] Available Scrapy objects:
[s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s] crawler <scrapy.crawler.Crawler object at 0x0000026EA72752B0>
[s] item {}
[s] request <GET http://mil.news.sina.com.cn/2011-03-31/1342640379.html>
[s] response <200 http://mil.news.sina.com.cn/2011-03-31/1342640379.html>
[s] settings <scrapy.settings.Settings object at 0x0000026EA8586940>
[s] spider <DefaultSpider 'default' at 0x26ea884bb38>
[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 browser
In [1]: response.status
Out[1]: 200

在交互式环境里设置自定义headers

$ scrapy shell --nolog
...
...
>>> from scrapy import Request
>>> req = Request('douban.com', headers = {'User-Agent' : '...'})
>>> fetch(req)

if you just want to set user agent

scrapy shell -s USER_AGENT='useragent' 'https://movie.douban.com'

4. 命令行下向爬虫传参数

scrapy crawl myspider -a category=electronics

在爬虫中获取参数,直接通过参数名获取,如下面代码中的category

import scrapy

class MySpider(scrapy.Spider):
name = 'myspider' def __init__(self, category=None, *args, **kwargs):
super(MySpider, self).__init__(*args, **kwargs)
self.start_urls = ['http://www.example.com/categories/%s' % category]
# ...

5. 去除网页中的\r\n

用xpath中的normalize-space

以及extract_first是个好东西,还能加默认值

item['content'] = response.xpath('normalize-space(//div[@class="blkContainerSblkCon" and @id="artibody"])').extract_first(default = '')

6. 以编程方式停止一个爬虫

方法是抛出一个内置的异常CloseSpider

exception scrapy.exceptions.CloseSpider(reason='cancelled')

This exception can be raised from a spider callback to request the spider to be closed/stopped. Supported arguments:

Parameters: reason (str) – the reason for closing

def parse_page(self, response):
if 'Bandwidth exceeded' in response.body:
raise CloseSpider('bandwidth_exceeded')

7. [mysql] Incorrect string value: '\xF0\x9F\x8C\xB9' for column 'title' at row 1

连接数据库时的charset参数设置成utf8mb4

8. 写入文件时为utf-8编码而不是中文

在settings.py 文件末加上 FEED_EXPORT_ENCODING = 'utf-8'

9. soome things about Item

>>> import scrapy
>>> class A(scrapy.Item):
... post_id = scrapy.Field()
... user_id = scrapy.Field()
... content = scrapy.Field()
...
>>> type(A)
<class 'scrapy.item.ItemMeta'>

这里的post_id和user_id可以存储任何类型的数据

取数据的时候也可以像是操作dic一样

>>> a = A(post_id = '12312312', author_id = '2342_author_id')
>>> a['post_id']
'12312312'
>>> a['author_id']
'2342_author_id'

如果field未被赋值,直接用dic['key']的方法取数据会报'KeyError',解决办法是改用get方法

>>> a.get('content', default = 'empty')
'empty'
>>> a.get('content', 'empty')
'empty'

判断Item中是否存在某个field以及是否被赋值

>>> 'name' in a   # name是否被赋值
False
>>> 'name' in a.fields # a的属性里是否有 'name
False
>>> 'content' in a # content是否被赋值
False
>>> 'content' in a.fields
True

建议所有dic['key']都改成dic.get('key', '')

10. 日志写入到文件

在settings.py中插入

LOG_STDOUT = True
LOG_FILE = 'scrapy_log.txt'

或

scrapy crawl MyCrawler -s LOG_FILE=/var/log/crawler_mycrawler.log

Reference

  1. Set headers for scrapy shell request

  2. Scrapy 1.5 documentation

[Scrapy] Some things about Scrapy的更多相关文章

  1. 从零安装Scrapy心得 | Install Python Scrapy from scratch

    1. 介绍 Scrapy,是基于python的网络爬虫框架,它能从网络上爬下来信息,是data获取的一个好方式.于是想安装下看看. 进到它的官网,安装的介绍页面 https://docs.scrapy ...

  2. Scrapy:学习笔记(2)——Scrapy项目

    Scrapy:学习笔记(2)——Scrapy项目 1.创建项目 创建一个Scrapy项目,并将其命名为“demo” scrapy startproject demo cd demo 稍等片刻后,Scr ...

  3. scrapy基础知识之 Scrapy 和 scrapy-redis的区别:

    Scrapy 和 scrapy-redis的区别 Scrapy 是一个通用的爬虫框架,但是不支持分布式,Scrapy-redis是为了更方便地实现Scrapy分布式爬取,而提供了一些以redis为基础 ...

  4. scrapy的安装,scrapy创建项目

    简要: scrapy的安装 # 1)pip install scrapy -i https://pypi.douban.com/simple(国内源) 一步到位 # 2) 报错1: building ...

  5. Scrapy:Python实现scrapy框架爬虫两个网址下载网页内容信息——Jason niu

    import scrapy class DmozSpider(scrapy.Spider): name ="dmoz" allowed_domains = ["dmoz. ...

  6. Scrapy基础(十四)————Scrapy实现知乎模拟登陆

    模拟登陆大体思路见此博文,本篇文章只是将登陆在scrapy中实现而已 之前介绍过通过requests的session 会话模拟登陆:必须是session,涉及到验证码和xsrf的写入cookie验证的 ...

  7. scrapy下载图片报[scrapy.downloadermiddlewares.robotstxt] DEBUG: Forbidden by robots.txt:错误

    本文转自:http://blog.csdn.net/zzk1995/article/details/51628205 先说结论,关闭scrapy自带的ROBOTSTXT_OBEY功能,在setting ...

  8. 【Scrapy】关于使用Scrapy框架爬虫遇到的问题1

    class testScrapy(scrapy.Spider): name = "testLogs" allowed_domains=["cnblogs.com" ...

  9. scrapy(一)scrapy 安装问题

    一.安装scrapy pip install scrapy 二.出现Microsoft Visual C++ 14.0相关问题 注:若出现以下安装错误 building 'twisted.test.r ...

随机推荐

  1. lightoj 1028 - Trailing Zeroes (I)(素数筛)

    We know what a base of a number is and what the properties are. For example, we use decimal number s ...

  2. 树形dp poj2342 Anniversary party * 求最大价值

    Description There is going to be a party to celebrate the 80-th Anniversary of the Ural State Univer ...

  3. 牛客网暑期ACM多校训练营(第三场)---A.PACM Team

    链接:https://www.nowcoder.com/acm/contest/141/A 来源:牛客网 题目描述 Eddy was a contestant participating in ACM ...

  4. [DP]最长递增子序列

    #include <iostream> #include <limits.h> #include <vector> #include <algorithm&g ...

  5. 谈谈你对HTML语义化的理解。

    1.什么是HTML语义化? 基本上都是围绕着几个主要的标签,像标题(h1-h6),列表(li),强调(strong em)等. 根据内容的语义化(内容结构化),选择合适的标签(代码语义化),便于开发者 ...

  6. ubuntu下配置JDK,Eclipse,android开发环境

    前言:由于我的电脑是64位的,所以下面使用的jdk ; eclipse : 包括我安装的 ubuntu12.0.4LTS 都是64位的:如果你是32位请下载32位的系统以及jdk,eclipse等软件 ...

  7. hbase数据备份或者容灾方案

    HBase的数据备份或者容灾方案有这几种:Distcp,CopyTable,Export/Import,Snapshot,Replication,以下分别介绍(以下描述的内容均是基于0.94.20版本 ...

  8. Spring SpringMVC myBatis(简称SSM)理解

    1对Spring的理解 (1)spring是什么? spring是Java SE(Java 标准版本)/Java EE(Java 企业版本)开发应用框架. (2)spring的作用 (a)spring ...

  9. 如何部署 H5 游戏到云服务器?

    在自学游戏开发的路上,最有成就感的时刻就是将自己的小游戏做出来分享给朋友试玩,原生的游戏开可以打包分享,小游戏上线流程又长,那 H5 小游戏该怎么分享呢?本文就带大家通过 nginx 将构建好的 H5 ...

  10. 使用Bookinfo应用测试Kuma服务网格

    最近,开源API管理平台Kong服务供应商近日放出了新的开源项目Kuma.本文尝试将 bookinfo 应用部署在 Kuma 网格中,以便帮助大家更好的理解 Kuma 项目.   Kuma是能用于管理 ...