Ric*_*ard 2 python lxml pyquery
我试图使用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()
Run Code Online (Sandbox Code Playgroud)
这会产生(注意冒号和句号前的空格):
Randomized and non-randomized patients in clinical trials :
experiences with comprehensive cohort studies .
Run Code Online (Sandbox Code Playgroud)
如何阻止pyquery在文本中插入空格?
看完后PyQuery的源我发现text()方法返回以下内容:
return ' '.join([t.strip() for t in text if t.strip()])
Run Code Online (Sandbox Code Playgroud)
这意味着非空标签的内容将始终由单个空格分隔.我想问题是html的文本表示没有明确定义,所以我不认为它可以被认为是一个错误 - 特别是因为text()文档中的示例确实如此:
>>> doc = PyQuery('<div><span>toto</span><span>tata</span></div>')
>>> print(doc.text())
toto tata
Run Code Online (Sandbox Code Playgroud)
如果您想要其他行为,请尝试实现您自己的版本text().您可以使用原始版本获取灵感,因为它只有10行左右.
| 归档时间: |
|
| 查看次数: |
122 次 |
| 最近记录: |