在脚本中运行 Scrapy

除了常用的 scrapy crawl 来启动 Scrapy,也可以使用 API 在脚本中启动 Scrapy。

需要注意的是,Scrapy 是在 Twisted 异步网络库上构建的,因此其必须在 Twisted reactor 里运行。

另外,在 spider 运行结束后,必须自行关闭 Twisted reactor。这可以通过 CrawlerRunner.crawl 所返回的对象中添加回调函数来实现。

示例:

from twisted.internet import reactor
from scrapy.crawler import CrawlerRunner
from scrapy.utils.project import get_project_settings runner = CrawlerRunner(get_project_settings()) # 'followall' is the name of one of the spiders of the project.
d = runner.crawl('followall', domain='scrapinghub.com')
d.addBoth(lambda _: reactor.stop())
reactor.run() # the script will block here until the crawling is finished
#Running spiders outside projects it’s not much different. You have to create a generic Settings object and populate it as needed (See 内置设定参考手册 for the available settings), instead of using the configuration returned by get_project_settings. #Spiders can still be referenced by their name if SPIDER_MODULES is set with the modules where Scrapy should look for spiders. Otherwise, passing the spider class as first argument in the CrawlerRunner.crawl method is enough. from twisted.internet import reactor
from scrapy.spider import Spider
from scrapy.crawler import CrawlerRunner
from scrapy.settings import Settings class MySpider(Spider):
# Your spider definition
... settings = Settings({'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'})
runner = CrawlerRunner(settings) d = runner.crawl(MySpider)
d.addBoth(lambda _: reactor.stop())
reactor.run() # the script will block here until the crawling is finished

同一进程运行多个 spider

默认情况下,当执行 scrapy crawl 时,Scrapy 每个进程运行一个 spider。当然,Scrapy通过内部(internal)API 也支持单进程多个 spider。

示例:

from twisted.internet import reactor, defer
from scrapy.crawler import CrawlerRunner
from scrapy.utils.project import get_project_settings runner = CrawlerRunner(get_project_settings())
dfs = set()
for domain in ['scrapinghub.com', 'insophia.com']:
d = runner.crawl('followall', domain=domain)
dfs.add(d) defer.DeferredList(dfs).addBoth(lambda _: reactor.stop())
reactor.run() # the script will block here until all crawling jobs are finished

相同的例子,不通过链接(chaining)deferred 来线性运行 spider:

from twisted.internet import reactor, defer
from scrapy.crawler import CrawlerRunner
from scrapy.utils.project import get_project_settings runner = CrawlerRunner(get_project_settings()) @defer.inlineCallbacks
def crawl():
for domain in ['scrapinghub.com', 'insophia.com']:
yield runner.crawl('followall', domain=domain)
reactor.stop() crawl()
reactor.run() # the script will block here until the last crawl call is finished

分布式爬虫(Distributed crawls)

Scrapy 并没有提供内置的机制支持分布式(多服务器)爬取。不过还是有办法进行分布式爬取,取决于要怎么分布了。

如果有很多 spider,那分布负载最简单的方法就是启动过个 Scrapyd,并分配到不同机器上。

如果想要在多个机器上运行一个单独的 spider,可以将要爬取的 url 进行分块,并发送给 spider。例如:

首先,准备要爬取的 url 列表,并分配到不同的文件 url 里:

http://somedomain.com/urls-to-crawl/spider1/part1.list
http://somedomain.com/urls-to-crawl/spider1/part2.list
http://somedomain.com/urls-to-crawl/spider1/part3.list

接着在3个不同的 Scrapyd 服务器中启动 spider。spider 会接受一个(spider)参数part,该参数表示要爬取的分块:

curl http://scrapy1.mycompany.com:6800/schedule.json -d project=myproject -d spider=spider1 -d part=1
curl http://scrapy2.mycompany.com:6800/schedule.json -d project=myproject -d spider=spider1 -d part=2
curl http://scrapy3.mycompany.com:6800/schedule.json -d project=myproject -d spider=spider1 -d part=3

避免被禁止

有些网站实现了特定的机制,以一定的规则来避免被爬虫爬取。与这些规则打交道并不容易,需要技巧,有时候也需要特别的基础。

下面是处理这些站点的建议:

  • 使用 user agent 池,轮流选择之一来作为 user agent。池中包含常见的浏览器的 user agent
  • 禁止 cookies(参考 COOKIES_ENABLED),有些站点会使用 cookies 来发现爬虫的轨迹。
  • 设置下载延迟(2 或更高)。参考 DOWNLOAD_DELAY 设置。
  • 如果可行,使用 Google cache 来爬取数据,而不是直接访问站点。
  • 使用 IP 池。例如免费的 Tor 项目或付费服务(ProxyMesh)。
  • 使用高度分布式的下载器(downloader)来绕过禁止(ban),您就只需要专注分析处理页面。这样的例子有:Crawlera

动态创建 Item 类

对于有些应用,item 的结构由用户输入或者其它变化的情况所控制。你可以动态创建 class。

from scrapy.item import DictItem, Field

def create_item_class(class_name, field_list):
fields = {field_name: Field() for field_name in field_list} return type(class_name, (DictItem,), {'fields': fields})

爬虫:Scrapy17 - Common Practices的更多相关文章

  1. Scrapy:运行爬虫程序的方式

    Windows 10家庭中文版,Python 3.6.4,Scrapy 1.5.0, 在创建了爬虫程序后,就可以运行爬虫程序了.Scrapy中介绍了几种运行爬虫程序的方式,列举如下: -命令行工具之s ...

  2. c#面试题汇总

    下面的参考解答只是帮助大家理解,不用背,面试题.笔试题千变万化,不要梦想着把题覆盖了,下面的题是供大家查漏补缺用的,真正的把这些题搞懂了,才能“以不变应万变”.回答问题的时候能联系做过项目的例子是最好 ...

  3. (翻译)《Hands-on Node.js》—— Introduction

    今天开始会和大熊君{{bb}}一起着手翻译node的系列外文书籍,大熊负责翻译<Node.js IN ACTION>一书,而我暂时负责翻译这本<Hands-on Node.js> ...

  4. 传智播客DotNet面试题

    技术类面试.笔试题汇总(整理者:杨中科,部分内容从互联网中整理而来) 注:标明*的问题属于选择性掌握的内容,能掌握更好,没掌握也没关系. 下面的参考解答只是帮助大家理解,不用背,面试题.笔试题千变万化 ...

  5. Interview

    下面的题是供大家查漏补缺用的,真正的把这些题搞懂了,才能"以不变应万变". 回答问题的时候能联系做过项目的例子是最好的,有的问题后面我已经补充联系到项目中的对应的案例了. 1.简述 ...

  6. 转一篇关于Unity的PlayMaker

    这篇文章转自http://va.lent.in/should-you-use-playmaker-in-production/ 此文作者大概深受其苦,吐槽了playmaker的多个蛋疼的地方,这其实说 ...

  7. .NET面试必备(整理)

    1.简述 private. protected. public. internal 修饰符的访问权限. private : 私有成员, 在类的内部才可以访问.public : 公共成员,完全公开,没有 ...

  8. C# Development 13 Things Every C# Developer Should Know

    https://dzone.com/refcardz/csharp C#Development 13 Things Every C# Developer Should Know Written by ...

  9. Understanding Python metaclasses

    转载:https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/ None of the existing article ...

随机推荐

  1. Linux_vsftpd服务配置

    首先安装Linux 企业版第一张光盘中的vsftpd-2.0.1-5.i386.rpm#rpm –ivh /media/cdrom/RedHat/RPMS/vsftpd-3.0.1-5.i386.rp ...

  2. 动态规划(一)POJ1163

    动态规划算法是比较实用的算法之一,结合实际问题能更好的熟悉这个算法 下面以POJ1163为例子 1. 首先是题目大意 :在给定的一个数字三角形中找到一条自上而下的路径,路径每一步只能左下或者右下,最后 ...

  3. 【2017 ICPC亚洲区域赛沈阳站 K】Rabbits(思维)

    Problem Description Here N (N ≥ 3) rabbits are playing by the river. They are playing on a number li ...

  4. ABAP术语-Business Framework Architecture

    Business Framework Architecture 原文:http://www.cnblogs.com/qiangsheng/archive/2007/12/29/1019277.html ...

  5. IDEA的使用方法(三)(改变字体主题)

    今天正式写代码的时候发现,一开始由于破解的太随意,没有设定好主题和字体现在看的有点昏,那么接下来就发一个该如何改变IDEA的字体和主题的教程: File——>setting——>Edito ...

  6. html样式不兼容 详解(转)

    网站对火狐不兼容的原因以及解决的方法 1.DOCTYPE 影响 CSS 处理 2.FF: div 设置 margin-left, margin-right 为 auto 时已经居中, IE 不行 3. ...

  7. Vue 2.0 组件库总结

    UI组件 element - 饿了么出品的Vue2的web UI工具套件 Vux - 基于Vue和WeUI的组件库 mint-ui - Vue 2的移动UI元素 iview - 基于 Vuejs 的开 ...

  8. iWebShop产品功能技术优势有什么?

    iwebshop基于iweb si 框架开发,在获得iweb si 技术平台支持的条件下,iwebshop可以轻松满足用户量级百万至千万级的大型电子商务网站的性能要求.站点的集群与分布式技术(分布式计 ...

  9. thinkphp 3.2中依靠关联模型来关联三个表

    这里说的是用thinkphp3.2关联模型关联三个表 根据用户表查询出三个表的数据,需要两个model来配合,第一个model是根据user表来查询到班级的信息,然后第二个model是根绝banji中 ...

  10. 《python编程从入门到实践》第六章笔记

    1.字典 字典:一系列键-值对,每一个键都与每一个值相关联.与键相关联的值可以是数字.字符串.列表和字典. 最简单的字典只有一个键值对. eg: alien = {'color':'green','p ...