2012-12-04 69 views
1

我目前使用BeautifulSoup來提取HTML元素和屬性。
我也想知道提取的每個元素的嵌套級別。如何使用BeautifulSoup提取HTML元素的嵌套級別?

例如:

示例HTML:

<html> 
    <head> 
    <title>Element Attributes Test</title> 
    </head> 
    <body> 
    <div id="abc"> 
     <ol id="def"> 
     <li class="testItem"> <a href="http://testpage.html"> 
     </li> 
     <li class="testItem"> <table id="testTable"> 
       <tr> 
       <td> 
        <div id="testDiv"> 
        </div> 
       </td> 
       </tr> 
      </table> 
     </li> 
     </ol> 
    </div> 
    </body> 
</html> 

我想獲得的路徑信息如在路徑列輸出中的特定元素。

---------------------------------- 
Element | Attribute | Path 
---------------------------------- 
html | None  | document 
---------------------------------- 
head | None  | html 
---------------------------------- 
title | None  | html.head 
---------------------------------- 
body | None  | html 
---------------------------------- 
div  | id="abc" | html.body 
----------------------------------- 
ol  | id="def" | html.body.div 
----------------------------------- 
li  | class=".."| html.body.div.ol 
----------------------------------- 
a  | href=".." | html.body.div.ol.li 
----------------------------------- 
li  | class=".."| html.body.div.ol 
----------------------------------- 
table | id="..." | html.body.div.old.li 
----------------------------------- 
tr  | None  | html.body.div.li.table 
----------------------------------- 

我能夠提取元素及其關聯的屬性,但無法找到合適的方法來獲取該特定元素的路徑。

如何使用BeautifulSoup提取相同的圖像? 有沒有其他庫可以用來提取它們?

在此先感謝。

回答

1

你可能會採取以下方法在獲得自下而上的路徑,所有的HTML元素

>>> for elem in soup.findAll(): 
    path = '.'.join(reversed([p.name for p in elem.parentGenerator() if p])) 
    print "{:10}|{:60}|{:10}".format(elem.name,elem.attrs, path) 


html  |[]               |[document] 
head  |[]               |[document].html 
title  |[]               |[document].html.head 
body  |[]               |[document].html 
div  |[(u'id', u'abc')]           |[document].html.body 
ol  |[(u'id', u'def')]           |[document].html.body.div 
li  |[(u'class', u'testItem')]         |[document].html.body.div.ol 
a   |[(u'href', u'http://testpage.html')]      |[document].html.body.div.ol.li 
li  |[(u'class', u'testItem')]         |[document].html.body.div.ol 
table  |[(u'id', u'testTable')]          |[document].html.body.div.ol.li 
tr  |[]               |[document].html.body.div.ol.li.table 
td  |[]               |[document].html.body.div.ol.li.table.tr 
div  |[(u'id', u'testDiv')]          |[document].html.body.div.ol.li.table.tr.td 
>>> 
+0

太謝謝你了。 – user1652054

0

爲了讓你可以嘗試這樣的路徑:

[i.name for i in soup.findAll('div',{'id':'testDiv'})[0].findParents()] 

輸出:

['td', 'tr', 'table', 'li', 'ol', 'div', 'body', 'html', u'[document]'] 

或:

'.'.join([i.name for i in soup.findAll('div',{'id':'testDiv'})[0].findParents()][::-1]) 

得到它爲AA串:

u'[document].html.body.div.ol.li.table.tr.td'