【发布时间】:2012-01-21 22:49:00
【问题描述】:
我有以下(简化的)代码,它使用以下源:
<html>
<p>line 1</p>
<div>
<a>line 2</a>
</div>
</html>
soup = BeautifulSoup('<html><p>line 1</p><div><a>line 2</a></div></html>')
ele = soup.find('p').nextSibling
somehow_print_tag_of_ele_here
我想得到ele的标签,在本例中是“div”。但是,我似乎只能获得其孩子的标签。我错过了一些简单的东西吗?我以为我可以做 ele.tag.name,但这是一个例外,因为 tag 是 None。
#Below correctly prints the div element "<div><a>line 2</a></div>"
print ele
#Below prints "None". Printing tag.name is an exception since tag is None
print ele.tag
#Below prints "a", the child of ele
allTags = ele.findAll(True)
for e in allTags:
print e.name
此时,我正在考虑在获取 ele 的父级的过程中做一些事情,然后获取父级的子级标签,并计算 ele 有多少上兄弟姐妹,倒数到正确的子级标签。这似乎很荒谬。
【问题讨论】:
标签: tags beautifulsoup