Python爬虫scrapy

前端之家收集整理的这篇文章主要介绍了Python爬虫scrapy前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

今天带来scrapy的第二讲,讲道理这个爬虫框架确实不错,但是用起来很多地方好坑,需要大家自己总结了,接下来我们先好好讲讲scrapy的用法机制。

1 命令行工具

list

列出当前项目中所有可用的spider。每行输出一个spider。

  1. $ scrapy listspider1
  2. spider2
fetch

使用Scrapy下载器(downloader)下载给定的URL,并将获取到的内容送到标准输出

  1. $ scrapy fetch --nolog http://www.example.com/some/page.html[ ... html content here ... ]
view

在浏览器中打开给定的URL,并以Scrapy spider获取到的形式展现。

  1. $ scrapy view http://www.example.com/some/page.html[ ... browser starts ... ]
genspider

这仅仅是创建spider的一种快捷方法。该方法可以使用提前定义好的模板来生成spider。您也可以自己创建spider的源码文件

  1. $ scrapy genspider -t basic example example.com
  2. Created spider 'example' using template 'basic' in module:
  3.   mybot.spiders.example

2 Spiders

Spider类定义了如何爬取某个(或某些)网站。包括了爬取的动作(例如:是否跟进链接)以及如何从网页的内容提取结构化数据(爬取item)。 换句话说,Spider就是您定义爬取的动作及分析某个网页(或者是有些网页)的地方。

基本方法这里不做讲解,来看一下今天要讲的。

如果您想要修改最初爬取某个网站的Request对象,您可以重写(override)该方法。 例如,如果您需要在启动时以POST登录某个网站,你可以这么写:

  1. class MySpider(scrapy.Spider):
  2.     name = 'myspider'
  3.  
  4.     def start_requests(self):
  5.         return [scrapy.FormRequest("http://www.example.com/login",
  6.                                    formdata={'user': 'john', 'pass': 'secret'},
  7.                                    callback=self.logged_in)]    def logged_in(self, response):
  8.         # here you would extract links to follow and return Requests for
  9.         # each of them, with another callback
  10.         pass

除了 start_urls 你也可以直接使用 start_requests()

  1. import scrapyfrom myproject.items import MyItemclass MySpider(scrapy.Spider):
  2.     name = 'example.com'
  3.     allowed_domains = ['example.com']    def start_requests(self):
  4.         yield scrapy.Request('http://www.example.com/1.html', self.parse)        yield scrapy.Request('http://www.example.com/2.html', self.parse)        yield scrapy.Request('http://www.example.com/3.html', self.parse)    def parse(self, response):
  5.         for h3 in response.xpath('//h3').extract():            yield MyItem(title=h3)        for url in response.xpath('//a/@href').extract():            yield scrapy.Request(url, callback=self.parse)

可以看到我们在这个spider里面没有写stat_url,直接通过start_requests方法进行爬取。

  • parse(response)
    这个方法大家已经不再陌生,而且用起来很简单。
    在单个回调函数中返回多个Request以及Item的例子:

  1. import scrapyclass MySpider(scrapy.Spider):
  2.     name = 'example.com'
  3.     allowed_domains = ['example.com']
  4.     start_urls = [        'http://www.example.com/1.html',        'http://www.example.com/2.html',        'http://www.example.com/3.html',
  5.     ]    def parse(self, response):
  6.         sel = scrapy.Selector(response)        for h3 in response.xpath('//h3').extract():            yield {"title": h3}        for url in response.xpath('//a/@href').extract():            yield scrapy.Request(url, callback=self.parse)
  • Spider arguments
    Spider arguments are passed through the crawl command using the -a
    option. For example:

  1. import scrapyclass MySpider(scrapy.Spider):
  2.     name = 'myspider'
  3.  
  4.     def __init__(self, category=None, *args, **kwargs):
  5.         super(MySpider, self).__init__(*args, **kwargs)
  6.         self.start_urls = ['http://www.example.com/categories/%s' % category]        # ...

注意这里的init方法,可以在里面定义start_urls。

  1. scrapy crawl myspider -a category=electronics

我们运行上面这个命令,就是把category=electronics传给myspider。

  • 爬取规则(Crawling rules)
    接下来给出配合rule使用CrawlSpider的例子:

  1. mport scrapyfrom scrapy.spiders import CrawlSpider, Rulefrom scrapy.linkextractors import LinkExtractorclass MySpider(CrawlSpider):
  2.     name = 'example.com'
  3.     allowed_domains = ['example.com']
  4.     start_urls = ['http://www.example.com']
  5.  
  6.     rules = (        提取匹配 'category.PHP' (但不匹配 'subsection.PHP') 的链接并跟进链接(没有callback意味着follow默认为True)
  7.         Rule(LinkExtractor(allow=('category\.PHP', ), deny=('subsection\.PHP', ))),        提取匹配 'item.PHP' 的链接并使用spider的parse_item方法进行分析
  8.         Rule(LinkExtractor(allow=('item\.PHP', )), callback='parse_item'),
  9.     )    def parse_item(self, response):
  10.         self.logger.info('Hi, this is an item page! %s', response.url)
  11.  
  12.         item = scrapy.Item()
  13.         item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
  14.         item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()
  15.         item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()        return item

LinkExtractor是一个 Link Extractor 对象。 其定义了如何从爬取到的页面提取链接。 是一个 Link Extractor 对象。 其定义了如何从爬取到的页面提取链接

callback是一个callable或string(该spider中同名的函数将会被调用)。 从link_extractor中每获取链接时将会调用函数。该回调函数接受一个response作为其第一个参数, 并返回一个包含 Item 以及(或) Request 对象(或者这两者的子类)的列表(list)。

注意我们这里callback = parse_item返回的就是item。

该spider将从example.com的首页开始爬取,获取category以及item的链接并对后者使用 parse_item方法。 当item获得返回(response)时,将使用XPath处理HTML并生成一些数据填入 Item 中。

3 Items

爬取的主要目标就是从非结构性的数据源提取结构性数据,例如网页。 Scrapy spider可以以python的dict来返回提取的数据.

Item使用简单的class定义语法以及 Field 对象来声明。例如:

  1. import scrapyclass Product(scrapy.Item):
  2.     name = scrapy.Field()
  3.     price = scrapy.Field()
  4.     stock = scrapy.Field()
  5.     last_updated = scrapy.Field(serializer=str)
  • 创建item

  1. >>> product = Product(name='Desktop PC', price=1000)>>> print product
  2. Product(name='Desktop PC', price=1000)
  1. >>> product['name']
  2. Desktop PC>>> product.get('name')
  3. Desktop PC>>> product['price']1000>>> product['last_updated']
  4. Traceback (most recent call last):
  5.     ...
  6. KeyError: 'last_updated'>>> product.get('last_updated', 'not set')not set>>> product['lala'] # getting unknown fieldTraceback (most recent call last):
  7.     ...
  8. KeyError: 'lala'>>> product.get('lala', 'unknown field')'unknown field'>>> 'name' in product  # is name field populated?True>>> 'last_updated' in product  # is last_updated populated?False>>> 'last_updated' in product.fields  # is last_updated a declared field?True>>> 'lala' in product.fields  # is lala a declared field?False
  1. >>> product.keys()
  2. ['price', 'name']>>> product.items()
  3. [('price', 1000), ('name', 'Desktop PC')]
  • 扩展Item
    您可以通过继承原始的Item来扩展item(添加更多的字段或者修改某些字段的元数据)。

  1. class DiscountedProduct(Product):
  2.     discount_percent = scrapy.Field(serializer=str)
  3.     discount_expiration_date = scrapy.Field()

4 Item Pipeline

其实在之前我们就已经把数据放到item里面,并保存到本地json文件中。但发现好像还差点什么,没错就是Item Pipeline
以下是item pipeline的一些典型应用:

  • 清理HTML数据

  • 验证爬取的数据(检查item包含某些字段)

  • 查重(并丢弃)

  • 将爬取结果保存到数据库

验证价格,同时丢弃没有价格的item

  1. from scrapy.exceptions import DropItemclass PricePipeline(object):
  2.  
  3.     vat_factor = 1.15
  4.  
  5.     def process_item(self, item, spider):
  6.         if item['price']:            if item['price_excludes_vat']:
  7.                 item['price'] = item['price'] * self.vat_factor            return item        else:            raise DropItem("Missing price in %s" % item)

process_item(self, item, spider)每个item pipeline组件都需要调用方法,这个方法必须返回一个具有数据的dict,或是 Item(或任何继承类)对象, 或是抛出 DropItem
异常,被丢弃的item将不会被之后的pipeline组件所处理。

将item写入JSON文件

以下pipeline将所有(从所有spider中)爬取到的item,存储到一个独立地 items.jl 文件,每行包含一个序列化为JSON格式的item:

  1. import jsonclass JsonWriterPipeline(object):
  2.     def __init__(self):
  3.         self.file = open('items.jl', 'wb')    def process_item(self, item, spider):
  4.         line = json.dumps(dict(item)) + "\n"
  5.         self.file.write(line)        return item
Write items to MongoDB
  1. import pymongoclass MongoPipeline(object):
  2.  
  3.     collection_name = 'scrapy_items'
  4.  
  5.     def __init__(self, mongo_uri, mongo_db):
  6.         self.mongo_uri = mongo_uri
  7.         self.mongo_db = mongo_db    @classmethod
  8.     def from_crawler(cls, crawler):
  9.         return cls(
  10.             mongo_uri=crawler.settings.get('MONGO_URI'),
  11.             mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
  12.         )    def open_spider(self, spider):
  13.         self.client = pymongo.MongoClient(self.mongo_uri)
  14.         self.db = self.client[self.mongo_db]    def close_spider(self, spider):
  15.         self.client.close()    def process_item(self, item, spider):
  16.         self.db[self.collection_name].insert(dict(item))        return item

上面的classmethod实际上是返回了一个MongoPipeline实例,并把mongo的参数初始化。

去重

一个用于去重的过滤器,丢弃那些已经被处理过的item。让我们假设我们的item有一个唯一的id,但是我们spider返回的多个item中包含有相同的id:

  1. from scrapy.exceptions import DropItemclass DuplicatesPipeline(object):
  2.     def __init__(self):
  3.         self.ids_seen = set()    def process_item(self, item, spider):
  4.         if item['id'] in self.ids_seen:            raise DropItem("Duplicate item found: %s" % item)        else:
  5.             self.ids_seen.add(item['id'])            return item

问题来了,我们的代码都写完了,但是这些pipiline代码放在哪里?
就是放在demo/demo/pipelines.py 里面,他同时可以定义多个类对item 进行处理。

  1. class TutorialPipeline(object):
  2.     def process_item(self, item, spider):
  3.         return item

这是默认的Pipeline代码,只有一个process_item方法

为了启用一个Item Pipeline组件,你必须将它的类添加到 [ITEM_PIPELINES
(http://scrapychs.readthedocs.io/zh_CN/1.0/topics/settings.html#std:setting-ITEM_PIPELINES) 配置,就像下面这个例子:
ITEM_PIPELINES = {
'myproject.pipelines.PricePipeline': 300,
'myproject.pipelines.JsonWriterPipeline': 800,
}

作者:我是上帝可爱多

猜你在找的Python相关文章