[Scrapy] Some things about Scrapy
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
[Scrapy] Some things about Scrapy的更多相关文章
- 从零安装Scrapy心得 | Install Python Scrapy from scratch
1. 介绍 Scrapy,是基于python的网络爬虫框架,它能从网络上爬下来信息,是data获取的一个好方式.于是想安装下看看. 进到它的官网,安装的介绍页面 https://docs.scrapy ...
- Scrapy:学习笔记(2)——Scrapy项目
Scrapy:学习笔记(2)——Scrapy项目 1.创建项目 创建一个Scrapy项目,并将其命名为“demo” scrapy startproject demo cd demo 稍等片刻后,Scr ...
- scrapy基础知识之 Scrapy 和 scrapy-redis的区别:
Scrapy 和 scrapy-redis的区别 Scrapy 是一个通用的爬虫框架,但是不支持分布式,Scrapy-redis是为了更方便地实现Scrapy分布式爬取,而提供了一些以redis为基础 ...
- scrapy的安装,scrapy创建项目
简要: scrapy的安装 # 1)pip install scrapy -i https://pypi.douban.com/simple(国内源) 一步到位 # 2) 报错1: building ...
- Scrapy:Python实现scrapy框架爬虫两个网址下载网页内容信息——Jason niu
import scrapy class DmozSpider(scrapy.Spider): name ="dmoz" allowed_domains = ["dmoz. ...
- Scrapy基础(十四)————Scrapy实现知乎模拟登陆
模拟登陆大体思路见此博文,本篇文章只是将登陆在scrapy中实现而已 之前介绍过通过requests的session 会话模拟登陆:必须是session,涉及到验证码和xsrf的写入cookie验证的 ...
- scrapy下载图片报[scrapy.downloadermiddlewares.robotstxt] DEBUG: Forbidden by robots.txt:错误
本文转自:http://blog.csdn.net/zzk1995/article/details/51628205 先说结论,关闭scrapy自带的ROBOTSTXT_OBEY功能,在setting ...
- 【Scrapy】关于使用Scrapy框架爬虫遇到的问题1
class testScrapy(scrapy.Spider): name = "testLogs" allowed_domains=["cnblogs.com" ...
- scrapy(一)scrapy 安装问题
一.安装scrapy pip install scrapy 二.出现Microsoft Visual C++ 14.0相关问题 注:若出现以下安装错误 building 'twisted.test.r ...
随机推荐
- 九度 题目1454:Piggy-Bank 完全背包
题目1454:Piggy-Bank 时间限制:1 秒 内存限制:128 兆 特殊判题:否 提交:1584 解决:742 题目描述: Before ACM can do anything, a budg ...
- 【Offer】[63] 【股票的最大利润】
题目描述 思路分析 测试用例 Java代码 代码链接 题目描述 假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少? 例如,一只股票在某些时间节点的价格为{9, ...
- MariaDB数据库自学一
在CentOS下安装Mariadb 数据库,命令: yum -y mariadb mariadb.server 等待几分钟后就可以自动完成安装了,然后启动对应的服务: systemctl start ...
- win7右下角声音图标不见了
场景:开机后发生右下角的声音图标不见了,马上google,可能性有两种图标隐藏或者系统错误 隐藏处理方式:右下角下打开自定义--> 将它调为显示和通知(发生不好使,估计是系统错误) 系统错误处理 ...
- java 简单框架的运用
Struts Struts是一个基于Sun J2EE平台的MVC框架,主要是采用Servlet和JSP技术来实现的. Struts框架可分为以下四个主要部分,其中三个就和MVC模式紧密相关: 1.模 ...
- (五)Linux内存管理zone_sizes_init
背景 Read the fucking source code! --By 鲁迅 A picture is worth a thousand words. --By 高尔基 说明: Kernel版本: ...
- 005:CSS三大重点之三:定位
目录 1:定位模式和边偏移 2:定位模式 静态定位 相对定位:移动位置:脱标.占位置 绝对定位:脱标.占有位置. 拼爹型 子绝父相 固定定位:脱标.占有位置. 3:定位模式转换 3:z-index 前 ...
- vue2.0生成二维码图片并且下载图片到本地兼容写法
vue生成二维码图片,这里使用的是qrcode.js 这个插件(亲测写法,兼容没有问题) 第一步,下载插件 需要注意,这里下载的是qrcodejs2 cnpm install --save qrcod ...
- Apache Hadoop集群安装(NameNode HA + SPARK + 机架感知)
1.主机规划 序号 主机名 IP地址 角色 1 nn-1 192.168.9.21 NameNode.mr-jobhistory.zookeeper.JournalNode 2 nn-2 ).HA的集 ...
- Mysql高手系列 - 第13篇:细说NULL导致的神坑,让人防不胜防
这是Mysql系列第13篇. 环境:mysql5.7.25,cmd命令中进行演示. 当数据的值为NULL的时候,可能出现各种意想不到的效果,让人防不胜防,我们来看看NULL导致的各种神坑,如何避免? ...