【问题标题】:Scrapy parsing different detail page from listingsScrapy从列表中解析不同的详细信息页面
【发布时间】:2017-10-05 07:15:38
【问题描述】:

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

第一个详细页面:

<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>

第三个详细页面:

<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:赋值前引用了局部变量“作者”

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

【问题讨论】:

    标签: python html css scrapy


    【解决方案1】:

    在您的情况下,strong_elements 看起来是空数组。所以for 循环不要运行。但是您在 for 循环中声明了 author 变量,并且在您的情况下,您在 yield 中使用了未声明的 author(因为 for 循环未运行)。在顶层声明 author 变量,如上面的 for 循环

    【讨论】:

      猜你喜欢
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 2016-03-25
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多