【发布时间】:2021-02-11 23:42:42
【问题描述】:
我正在使用 scrapy 从网站上抓取文本。我是scrapy和xpath的初学者。一些“div”标签包含一些文本,后跟一个链接,然后是一些文本。我想以相同的顺序提取文本和链接。
例如。
<div class="postbody">
<blockquote>
<div>
<cite>Anonymous wrote:</cite>Daycares have been open for at least six months. Some never closed during the pandemic. They seem to be doing fine.
<br />
<br /> Sorry, teachers. Vacation has to end sometime.
</div>
</blockquote>
<br />
<br /> Nah, they're not doing fine.
<br /> <a class="snap_shots" href="https://coronavirus.dc.gov/page/outbreak-data" target="_blank" rel="nofollow">https://coronavirus.dc.gov/page/outbreak-data</a>
<br />
<br /> /not a teacher
</div>
我只想要以下
Nah, they're not doing fine.
https://coronavirus.dc.gov/page/outbreak-data
/not a teacher
这是我到目前为止所做的。但它也会从不受欢迎的部分获取链接(如上例中的“blockquotes”标签)并将其附加到末尾。
post_text_response = post.xpath('.//div[@class="postbody"]/text()').getall()
post_link_attached = post.xpath('.//div[@class="postbody"]//a/@href')
post_text = re.sub(r'\s+', " ", "".join(post_text_response)).strip()
if(len(post_link_attached)>0):
post_text += " " + post_link_attached.extract_first()
- 如何在 scrapy 中使用 XPath 实现这一点?
- 虽然我的方法似乎可行,但在使用 xpath 时是否有更好的方法来忽略“blockquote”标签?
【问题讨论】: