这是我的 HTML:
<?xml version="1.0" encoding="UTF-8"?>
<div class="single-main">
<h3 class="description-area">Description</h3>
<p>bla bla bla
<br/> some text
<br/> some text here ,
<br/> other text here
</p>
</div>
我想获取整个文本,但在一个 XPath 表达式中。
这是我的代码:
response.xpath(".//h3[@class='description-area']/following-sibling::p
//text()[count(preceding-sibling::br) >= 0]").extract()[0]
但它只返回第一个 br
之前的文本(我知道为什么,那是因为我正在使用 .extract()[0]
并且如果我使用 . extract()[1] 和 [2] ....我会得到我想要的,但我必须使用 .extract[0] 因为它是一个可以做到这一点的平台。有没有XPath 返回整个文本但在一个字符串中而不是在多个字符串中?
最佳答案
string(/)
将返回整个文档的字符串值。
更新:要返回此 XPath 返回的四个单独的字符串,
.//h3[@class='description-area']/following-sibling::p//text()[count(preceding-sibling::br) >= 0]
作为单个字符串,将上述 XPath 类似地包装在 string()
中:
string(.//h3[@class='description-area']/following-sibling::p//text()[count(preceding-sibling::br) >= 0])
更新 2:但是 br
和 text()
操作不是必需的。您可以简单地获取 p
的字符串值:
string(.//h3[@class='description-area']/following-sibling::p)
关于html - 如何返回 XPath 表达式的单个字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37015039/