解析html时为什么我需要item.text和item.text_content()其他人

时间:2010-08-18 23:09:33

标签: python html parsing lxml

还在学习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

2 个答案:

答案 0 :(得分:10)

根据the docs方法here

  

返回元素的文本内容,包括文本内容   它的孩子,没有标记。

例如,

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 Elementa标记后面没有文字(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.Elementtext属性的含义同样适用于tail个对象。

答案 1 :(得分:3)

您可能会混淆lxml实现的不同且不兼容的接口 - lxml.etree项具有.text属性,而(例如)来自lxml.html的接口实现text_content {1}} lxml中包含的BeautifulSoup 的方法,.string属性... 有时 [[只有一个孩子的节点是一个字符串...]]。)。

是的, 本质上令人困惑,lxml选择实现自己的接口模拟或包含其他库,但它可以很方便.. ; - 。)