正如llasram所說,任何不在text
屬性中的文本都將在子節點的tail
屬性中。
作爲一個例子,這裏的提取文本塊(第一和其他)中的一個節點的所有最簡單的方法:
html = '<div>text1<span>childtext1</span>text2<span>childtext2</span>text3</div>'
import lxml.html # ...or lxml.etree as appropriate
div = lxml.html.fromstring(html)
texts = [div.text] + [child.tail for child in div]
# Result: texts == ['text1', 'text2', 'text3']
# ...and you are guaranteed that div[x].tail == texts[x+1]
# (which can be useful if you need to access or modify the DOM)
如果你寧願犧牲這層關係,以防止texts
從可能含有空字符串,你可以使用它代替:
texts = [div.text] + [child.tail for child in div if child.tail]
我還沒有與普通的舊STDLIB ElementTree的測試,這一點,但它應該與工作了。 (事只有一次,我看到了巴蒂爾Holloway的具體LXML-解決發生在我身上),我只是喜歡LXML因爲它有更好的支持HTML的ideosyncracies我通常已經安裝了lxml.html.clean
這看起來像一個錯誤。你有沒有嘗試過使用'findtext(path)'? – 2010-09-18 06:55:43
因爲我的回答顯然不能回答你的問題,你能否進一步解釋你在找什麼? – llasram 2010-09-19 09:18:51