首页 > 解决方案 > 只返回段落的第一部分,直到遇到子标签?

问题描述

这是使用 Scrapy。

我遇到以下类型的标记:

<p>Noting the presence of a footnote<sup>1</sup> is one common way for superscripts to be used.</p>

测试页面:
https ://html.com/tags/sup/

测试查询:

response.css('div.render p::text')[0].extract()

测试项目加载器:

loader.add_css("text", "div.render p::text")

试验结果:

注意到脚注的存在

预期测试:

注意脚注的存在是使用上标的一种常见方式。

问题:

如何获取段落的全文,忽略子标签?

标签: pythonscrapy

解决方案


我不知道scrapy是否有适当的选择器忽略嵌套的<sub>. 我建议您使用re模块来忽略孩子。顺便说一句,从长远来看,这不是一个解决方案。您不应该使用正则表达式解析 HTML。有关更多信息,请查看此线程RegEx match open tags except XHTML self-contained tags

尝试这个 :

import re
def parse(self,response):
    extracted_p_tag=response.css('div.render p').get()
    ignored_sup=re.sub('<sup>(.*)</sup>','',extracted_p_tag)

推荐阅读