我正在尝试使用pyquery 1.2从元素中获取一些文本。显示的文本中没有空格,但是pyquery是插入空格。
这是我的代码:
from pyquery import PyQuery as pq
html = '<h1><span class="highlight" style="background-color:">Randomized</span> and <span class="highlight" style="background-color:">non-randomized</span> <span class="highlight" style="background-color:">patients</span> in <span class="highlight" style="background-color:">clinical</span> <span class="highlight" style="background-color:">trials</span>: <span class="highlight" style="background-color:">experiences</span> with <span class="highlight" style="background-color:">comprehensive</span> <span class="highlight" style="background-color:">cohort</span> <span class="highlight" style="background-color:">studies</span>.</h1>'
doc = pq(html)
print doc('h1').text()
这会产生(冒号和句点之前的注释空间):
Randomized and non-randomized patients in clinical trials :
experiences with comprehensive cohort studies .
如何停止向文本中插入空格的pyquery?
发布于 2015-04-13 10:45:51
在阅读了PyQuery
的来源之后,我发现text()
方法返回以下内容:
return ' '.join([t.strip() for t in text if t.strip()])
这意味着非空标记的内容将始终由单个空格分隔。我猜问题在于html的文本表示没有很好的定义,所以我不认为它是一个bug--特别是因为text()
文档中的示例就是这样做的:
>>> doc = PyQuery('<div><span>toto</span><span>tata</span></div>')
>>> print(doc.text())
toto tata
如果您想要另一种行为,请尝试实现您自己版本的text()
。您可以使用原始版本的灵感,因为它只有10行左右。
https://stackoverflow.com/questions/29602929
复制相似问题