2010-06-17 86 views
8

我有一個XML文檔,其內容是這樣的:如何使用BeautifulSoup訪問名稱空間的XML元素?

<xml> 
<web:Web> 
<web:Total>4000</web:Total> 
<web:Offset>0</web:Offset> 
</web:Web> 
</xml> 

我的問題是他們在使用Python庫一樣BeautifulSoup我怎麼上網?

xmlDom.web [「Web」]。Total?不起作用?

回答

8

BeautifulSoup本身不是DOM庫(它不實現DOM API)。爲了使事情更加複雜,你在這個xml片段中使用了命名空間。要分析具體的一塊XML,你會使用BeautifulSoup如下:

from BeautifulSoup import BeautifulSoup 

xml = """<xml> 
    <web:Web> 
    <web:Total>4000</web:Total> 
    <web:Offset>0</web:Offset> 
    </web:Web> 
</xml>""" 

doc = BeautifulSoup(xml) 
print doc.find('web:total').string 
print doc.find('web:offset').string 

如果你沒有使用命名空間,代碼看起來是這樣的:

from BeautifulSoup import BeautifulSoup 

xml = """<xml> 
    <Web> 
    <Total>4000</Total> 
    <Offset>0</Offset> 
    </Web> 
</xml>""" 

doc = BeautifulSoup(xml) 
print doc.xml.web.total.string 
print doc.xml.web.offset.string 

這裏的關鍵是, BeautifulSoup不知道(或關心)任何關於命名空間的內容。因此web:Web被視爲web:web標記,而不是屬於web命名空間的Web標記。雖然BeautifulSoup將web:web添加到xml元素字典,但python語法不會將web:web識別爲單個標識符。

您可以通過閱讀documentation瞭解關於它的更多信息。

+0

謝謝!現在完美運作。 我總是感到困惑,以什麼給find()..和這些命名空間的定義和他們寫的方式迷惑了我很多...任何鏈接清除所有這些將不勝感激! – demos 2010-06-17 05:19:59

+0

只是我已經給你的文檔鏈接...和大量的實驗。 – 2010-06-17 05:26:57

+0

'AttributeError:'NoneType'對象沒有屬性'string'' – 2014-01-25 22:35:21

6

這是一個老問題,但有些人可能不知道,至少BeautifulSoup 4確實處理命名空間以及如果傳遞'xml'作爲第二個參數的構造函數:

soup = BeautifulSoup("""<xml> 
<web:Web> 
<web:Total>4000</web:Total> 
<web:Offset>0</web:Offset> 
</web:Web> 
</xml>""", 'xml') 

print soup.prettify() 
<?xml version="1.0" encoding="utf-8"?> 
<xml> 
<Web> 
    <Total> 
    4000 
    </Total> 
    <Offset> 
    0 
    </Offset> 
</Web> 
</xml> 
+0

對於4.4.1-1版本(在ubuntu 64 16.04中)並不完全正確。由於評論有限。請參閱[鏈接](https://pastebin.com/Q99iK6tM) – 2018-03-10 09:56:16

0

你應該明確地定義你的根命名空間元素,使用xmlns:prefix="URI"語法(see examples here),然後通過BeautifulSoup的prefix:tag訪問屬性。請記住,你也應該明確地定義,如何BeautifulSoup應該處理你的文件,在這種情況下:

xml = BeautifulSoup(xml_content, 'xml')

相關問題