【问题标题】:How to parse iFrame content in crawl spider using Python如何使用 Python 在爬虫中解析 iFrame 内容
【发布时间】:2020-02-19 19:17:12
【问题描述】:

我成功解析了网站的主要内容,但回调没有调用第二个函数,所以我没有得到 iframe 的数据。网址是https://www.farfeshplus.com/Video.asp?ZoneID=297

蜘蛛代码如下:

    # -*- coding: utf-8 -*-
    import scrapy
    from scrapy.linkextractors import LinkExtractor
    from scrapy.spiders import CrawlSpider, Rule





    class YuSpider(CrawlSpider):
        name = 'yu'
        allowed_domains = ['farfeshplus.com']
        start_urls = ['https://www.farfeshplus.com/Video.asp?ZoneID=297']

        rules = (
            Rule(LinkExtractor(restrict_xpaths='//td[@class="text6"]'), callback='parse_item', follow=True),

        )

        def parse_item(self, response):
            for url in response.xpath('//html'):
                yield {
                    'NAME': url.xpath('//h1/div/text()').extract(),
                    }
                frames = url.xpath('//iframe[@width="750"]/@src').extract_first()

                yield scrapy.Request(url=frames, callback=self.parse_frame)

        def parse_frame(self, response):
            for f in response.xpath('//div[@class="rmp-content"]/video'):
                yield {
                    'URL': f.xpath('//div[@class="rmp-content"]/video/@src').extract(),

                }

尝试将 parse_item 的名称更改为 parse_start_url 但没有成功。

【问题讨论】:

  • parse_item 是否被调用?内部的for 循环是否有任何迭代? frames 在这些迭代中的价值是多少?
  • parse_item 被调用,显示名称。帧变量也得到它的值。它只是不调用 parse_frame

标签: python web-scraping scrapy


【解决方案1】:

如果我能很好地理解您的目的,我会尝试以这种方式修改您的代码:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule





class YuSpider(CrawlSpider):
    name = 'yu'
    allowed_domains = ['farfeshplus.com']
    start_urls = ['https://www.farfeshplus.com/Video.asp?ZoneID=297']

    rules = (
        Rule(LinkExtractor(restrict_xpaths='//td[@class="text6"]'), callback='parse_item', follow=True),

    )

    def parse_item(self, response):
        for url in response.xpath('//html'):

            response.meta['NAME']=url.xpath('//h1/div/text()').extract()
            frames = url.xpath('//iframe[@width="750"]/@src').extract_first()

            yield scrapy.Request(url=frames, callback=self.parse_frame, meta=response.meta)

    def parse_frame(self, response):
        name=response.meta['NAME']
        for f in response.xpath('//div[@class="rmp-content"]/video'):
            yield {
                'URL': f.xpath('//div[@class="rmp-content"]/video/@src').extract(),
                'NAME':name

            }

我认为这个问题与 parse_frame (read this) 中的两个 yield 指令有关。因此,我使用 response.meta 在 parse_itemparse_frame 方法之间传递名称。

【讨论】:

    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    相关资源
    最近更新 更多