找回密码
 立即注册

蜘蛛

2022-2-21 06:01| 发布者: 笨鸟自学网| 查看: 8740| 评论: 0

摘要: spider是定义一个特定站点(或一组站点)如何被抓取的类,包括如何执行抓取(即跟踪链接)以及如何从页面中提取结构化数据(即抓取项)。换言之,spider是为特定站点(或者在某些情况下,一组站点)定义爬行和解析页 ...


爬行蜘蛛示例

现在让我们来看一个例子,爬行蜘蛛的规则是:

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class MySpider(CrawlSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com']

    rules = (
        # Extract links matching 'category.php' (but not matching 'subsection.php')
        # and follow links from them (since no callback means follow=True by default).
        Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),

        # Extract links matching 'item.php' and parse them with the spider's method parse_item
        Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),
    )

    def parse_item(self, response):
        self.logger.info('Hi, this is an item page! %s', response.url)
        item = scrapy.Item()
        item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
        item['name'] = response.xpath('//td[@id="item_name"]/text()').get()
        item['description'] = response.xpath('//td[@id="item_description"]/text()').get()
        item['link_text'] = response.meta['link_text']
        url = response.xpath('//td[@id="additional_data"]/@href').get()
        return response.follow(url, self.parse_additional_page, cb_kwargs=dict(item=item))

    def parse_additional_page(self, response, item):
        item['additional_data'] = response.xpath('//p[@id="additional_data"]/text()').get()
        return item

此蜘蛛将开始爬行example.com的主页,收集类别链接和项目链接,并使用 parse_item 方法。对于每个项目响应,将使用XPath从HTML中提取一些数据,并使用 Item 都会装满它。


上一篇:命令行工具下一篇:选择器

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2025-8-31 12:09 , Processed in 0.016286 second(s), 18 queries .

Powered by Discuz! X3.5

© 2001-2017 Discuz Team. Template By 【未来科技】【 www.wekei.cn 】

返回顶部