我正在从列表页面抓取网站的详细信息页面,每个详细信息页面都有一些差异。
第一个详情页:
<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: local variable 'author' referenced before assignment
我在这里做错了什么?请问如何分别从每个页面获取作者和新闻日期。谢谢。
最佳答案
看起来 strong_elements
在您的情况下是空数组。所以 for
循环不运行。但是您在 for 循环中声明了 author
变量,并且您在 yield 中使用了 author
,但在您的 yield 中未声明(因为 for
循环未运行)案件。像上面的 for
循环一样在顶层声明 author
变量
关于python - Scrapy 从列表中解析不同的详细信息页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43828104/