2011-12-16 47 views
8

我有下面(簡化)的代碼,它使用下面的源:BeautifulSoup:獲得元素本身的標籤名稱,而不是其子

<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,但這是一個例外,因爲標籤是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了,倒計數到正確的子標籤。這似乎很荒謬。

回答

18

ELE已經是一個標籤,試着這樣做:

soup = BeautifulSoup('<html><p>line 1</p><div><a>line 2</a></div></html>') 
print(soup.find('p').nextSibling.name) 

所以在你的榜樣它也不過

print(ele.name) 
+0

但是,這要求已經知道它是一個div標籤。 – user984003 2011-12-16 11:58:16

相關問題