递归爬网

2024-04-19 17:50:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是:我在主页上有一个列表(html-li),对于列表上的每个组件,我想在另一个页面中输入一些信息,将它们放在一个item元素中,然后在主页列表(html-li)上的其他元素上进行交互。我已经完成了第一段代码,但我是Python和Scrapy的新手,我发现了一些制作代码的困难。你知道吗

我得到了这个解决方案,但它为每个主列表元素生成两个项。你知道吗

class BoxSpider(scrapy.Spider):
    name = "mag"
    start_urls = [
        "http://www.example.com/index.html"
    ]

    def secondPage(self, response):
        secondPageItem = CinemasItem()
        secondPageItem['trailer'] = 'trailer'
        secondPageItem['synopsis'] = 'synopsis'
        yield secondPageItem

    def parse(self, response):

        for sel in response.xpath('//*[@id="conteudoInternas"]/ul/li'):

            item = CinemasItem()
            item['title'] = 'title'
            item['room'] = 'room'
            item['mclass'] = 'mclass'
            item['minAge'] = 'minAge'
            item['cover'] = 'cover'
            item['sessions'] = 'sessions'

            secondUrl = sel.xpath('p[1]/a/@href').extract()[0]

            yield item
            yield scrapy.Request(url=secondUrl, callback=self.secondPage)

有人能帮我只生成一个item元素,并填充“title”、“room”、“mclass”、“minAge”、“cover”、“sessions”、“trailer”、“sympsis”字段吗?而不是一个项目的'标题','房间','mclass','minAge','封面','会议'字段填写和其他'拖车','大纲'填写?你知道吗


Tags: self元素列表titleresponsehtmlcoverli
1条回答
网友
1楼 · 发布于 2024-04-19 17:50:41

您需要将在^{}内部的parse()中实例化的item传递给secondPage回调:

def parse(self, response):
    for sel in response.xpath('//*[@id="conteudoInternas"]/ul/li'):
        item = CinemasItem()
        item['title'] = 'title'
        item['room'] = 'room'
        item['mclass'] = 'mclass'
        item['minAge'] = 'minAge'
        item['cover'] = 'cover'
        item['sessions'] = 'sessions'

        secondUrl = sel.xpath('p[1]/a/@href').extract()[0]

        # see: we are passing the item inside the meta
        yield scrapy.Request(url=secondUrl, meta={'item': item}, callback=self.secondPage)

def secondPage(self, response):
    # see: we are getting the item from meta
    item = response.meta['item']

    item['trailer'] = 'trailer'
    item['synopsis'] = 'synopsis'
    yield item

另请参见:

相关问题 更多 >