Все еще учу 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
Accordng to the docs the text_content
method:
Returns the text content of the element, including the text content of its children, with no markup.
So for example,
import lxml.html as lh
data = """<a><b><c>blah</c></b></a>"""
doc = lh.fromstring(data)
print(doc)
# <Element a at b76eb83c>
doc
is the Element
a
. The a
tag has no text immediately following it (between the and the
. So
doc.text
is None
:
print(doc.text)
# None
but there is text after the c
tag, so doc.text_content()
is not None
:
print(doc.text_content())
# blah
PS. There is a clear description of the meaning of the text
attribute here. Although it is part of the docs for lxml.etree.Element
, I think the meaning of the text
and tail
attributes applies equally well to lxml.html.Element
objects.
Вы можете спутать разные и несовместимые интерфейсы, которые реализует lxml
- элементы lxml.etree
имеют атрибут .text
, в то время как (например) те из lxml.html реализуют метод text_content
(и методы из BeautifulSoup , также включены в ] lxml
, имеют атрибут .string
... иногда [[только узлы с одним дочерним элементом, который является строкой ...]]).
Да, по своей сути сбивает с толку то, что lxml
выбирает как для реализации собственных интерфейсов , так и для эмуляции или включения других библиотек, но это может быть удобно .. . ;-).