Scrapy从列表中解析不同的详细页面

问题描述 投票:2回答:1

我正在从列表页面抓取网站的详细信息页面,每个细节页面都有一些差异。

第1页详细信息:

<div class="td-post-content">
    <p style="text-align: justify;">
        <strong>[ Karda Natam ]</strong>
        <br>
        <strong>ITANAGAR, May 6:</strong> Nacho, Taksing, Siyum and ...
        <br> “Offices are without ...
    </p>
</div>

第二个细节页面:

<div class="td-post-content">
    <p style="text-align: justify;">
        <strong>Guwahati, May 6 (PTI)</strong> Sarbananda Sonowal today ...
        <br> “Books are a potent tool to create ...
    </p>
</div>

第3个详细页面:

<div class="td-post-content">
    <h3 style="text-align: justify;"><strong>Flights Of Fantasy</strong></h3>
    <p style="text-align: justify;">
        <strong>[ M Panging ]</strong>
        <br> This state of denial ...
    </p>
</div>

我试图解析作者并从详细信息页面发布日期:

class ArunachaltimesSpider(scrapy.Spider):
    ...
    ...

    def parse(self, response):
        urls = response.css("div.td-ss-main-content > div.td_module_16 > div.item-details > h3.entry-title > a::attr(href)").extract()
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse_detail)

        next = response.xpath("// ...')]/@href").extract_first()
        if next:
            yield scrapy.Request(url=next, callback=self.parse)

    def parse_detail(self, response):
        strong_elements = response.css("div.td-ss-main-content").css("div.td-post-content").css("p > strong::text").extract()
        for strong in strong_elements:
            if ', ' in strong:
                news_date = strong.split(', ')[1].replace(":", "")
            elif '[ ' and ' ]' in strong:
                author = strong
            else:
                news_date = None
                author = None
        yield {
            'author': author,
            'news_date': news_date
        }

但是我收到了这个错误:

UnboundLocalError:赋值前引用的局部变量“author”

我在这做错了什么?请问您如何分别从每个页面获取作者和新闻日期。谢谢。

python html css scrapy
1个回答
0
投票

看起来strong_elements在你的情况下是空数组。所以for循环不运行。但是你在for循环中声明了author变量,并且在你的情况下你使用的author未被声明(becoz for循环没有运行)。在上面的author循环中声明for变量

© www.soinside.com 2019 - 2024. All rights reserved.