首页 > 解决方案 > 使用 XPATH提取两个标签之间的所有文本(粗体)

问题描述

标签: pythonhtmlxpathscrapyxpath-1.0

解决方案


最快的方法可能是string(//p)使用特定的文本操作命令获取所有内容并进行拆分。

使用 XPath,您可以尝试:

获取所有标题(返回 5 个元素):

//b/text()

使用这些 XPath(返回 5*1 元素)获取相应的描述(包括斜体标记):

normalize-space(substring-before(substring-after(string(//p),//b[.="Introduction."]),//b[.="Aim."]))
normalize-space(substring-before(substring-after(string(//p),//b[.="Aim."]),//b[.="Methods."]))
normalize-space(substring-before(substring-after(string(//p),//b[.="Methods."]),//b[.="Results."]))
normalize-space(substring-before(substring-after(string(//p),//b[.="Results."]),//b[.="Conclusion."]))
normalize-space(substring-after(string(//p),//b[.="Conclusion."]))

如果您不知道标签之间的文本,您可以使用按位置索引 (//b[1],//b[2],...)。使用 count(//b) 知道最大值。

编辑:替代 XPaths:

normalize-space(//text()[preceding::b="Introduction." and following::b="Aim."])
normalize-space(//text()[preceding::b="Aim." and following::b="Methods."])
normalize-space(//text()[preceding::b="Methods." and following::b="Results."])
normalize-space(//text()[preceding::b="Results." and following::b="Conclusion."])
normalize-space(//text()[preceding::b="Conclusion."])

推荐阅读