【发布时间】:2012-07-25 12:26:44
【问题描述】:
我目前有点思路不清,真心希望你能给我一个提示: 最好用一小段示例代码来解释我的问题:
from lxml import etree
from io import StringIO
testStr = "<b>text0<i>text1</i><ul><li>item1</li><li>item2</li></ul>text2<b/><b>sib</b>"
parser = etree.HTMLParser()
# generate html tree
htmlTree = etree.parse(StringIO(testStr), parser)
print(etree.tostring(htmlTree, pretty_print=True).decode("utf-8"))
bElem = htmlTree.getroot().find("body/b")
print(".text only contains the first part: "+bElem.text+ " (which makes sense in some way)")
for text in bElem.itertext():
print(text)
输出:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<body>
<b>text0<i>text1</i><ul><li>item1</li><li>item2</li></ul>text2<b/><b>sib</b></b>
</body>
</html>
.text only contains the first part: text0 (which makes sense in some way)
text0
text1
item1
item2
text2
sib
我的问题:
我想直接访问"text2",或者获取所有文本部分的列表,只包括可以在父标签中找到的部分。
到目前为止,我只找到了itertext(),它确实显示了"text2"。
我还有其他方法可以检索"text2"吗?
现在你可能会问我为什么需要这个:
基本上itertext() 已经在做我想做的事了:
- 创建一个列表,其中包含在元素的子元素中找到的所有文本
- 但是,我想处理遇到的表和列表
一个不同的函数(随后创建一个列表结构
像这样:
["text0 text1",["item1","item2"],"text2"]或表格(1. 1 列的行,2. 有 2 列的行):["1. row, 1 col",["2. row, 1. col","2. row, 2. col"]])
也许我采取了完全错误的方法?
【问题讨论】:
-
你可以使用 encoding=unicode 和 tostring()
标签: python text html-parsing lxml