还在学习lxml。我发现有时候我无法使用item.text从树中获取项目的文本。如果我使用item.text_content()我很高兴。我不确定我明白为什么。任何提示将不胜感激
好吧,我不确定如何在不让你处理文件的情况下提供一个例子:
这里是我编写的一些代码,试图弄清楚为什么我没有得到我预期的文本:
theTree=html.fromstring(open(notmatched[0]).read())
text=[]
text_content=[]
notText=[]
hasText=[]
for each in theTree.iter():
if each.text:
text.append(each.text)
hasText.append(each) # list of elements that has text each.text is true
text_content.append(each.text_content()) #the text for all elements
if each not in hasText:
notText.append(each)
所以在我运行之后我会看
>>> len(notText)
3612
>>> notText[40]
<Element b at 26ab650>
>>> notText[40].text_content()
'(I.R.S. Employer'
>>> notText[40].text
答案 0 :(得分:10)
返回元素的文本内容,包括文本内容 它的孩子,没有标记。
例如,
text_content
import lxml.html as lh
data = """<a><b><c>blah</c></b></a>"""
doc = lh.fromstring(data)
print(doc)
# <Element a at b76eb83c>
是doc
Element
。 a
标记后面没有文字(a
和<a>
之间。<b>
为doc.text
:
None
但print(doc.text)
# None
代码后面有文字,因此c
不是doc.text_content()
:
None
PS。清楚地描述了print(doc.text_content())
# blah
属性{{3}}的含义。虽然它是text
文档的一部分,但我认为lxml.etree.Element
和text
属性的含义同样适用于tail
个对象。
答案 1 :(得分:3)
您可能会混淆lxml
实现的不同且不兼容的接口 - lxml.etree
项具有.text
属性,而(例如)来自lxml.html的接口实现text_content
{1}} lxml
中包含的BeautifulSoup, 的方法,.string
属性... 有时 [[只有一个孩子的节点是一个字符串...]]。)。
是的, 本质上令人困惑,lxml
选择实现自己的接口和模拟或包含其他库,但它可以很方便.. ; - 。)