停止pyquery在源HTML中没有空格的地方插入空格? - python

我正在尝试使用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在文本中插入空格?

python大神给出的解决方案

阅读PyQuery的source后,我发现text()方法返回以下内容:

return ' '.join([t.strip() for t in text if t.strip()])

这意味着非空标签的内容将始终用单个空格分隔。我想问题是html的文本表示形式定义不明确,所以我认为它不会被视为错误-尤其是因为text()文档中的示例确实做到了这一点:

>>> doc = PyQuery('<div><span>toto</span><span>tata</span></div>')
>>> print(doc.text())
toto tata

如果您想要其他行为,请尝试实现自己的text()版本。您可以使用原始版本作为灵感,因为它只有10行左右。