2013-03-06 55 views
0

所有元素如果我有這樣的事情:查找鑑於命名空間屬性

<p>blah</p> 
<p foo:bar="something">blah</p> 
<p foo:xxx="something">blah</p> 

我怎麼會得到beautifulsoup選擇與foo的命名空間的屬性的元素?

E.g.我想返回第二和第三個p元素。

回答

0

documentation

美麗的湯提供了一個名爲ATTRS,你可以在這些情況下使用特殊的說法。 ATTRS是作用就像參數的字典:

soup.findAll(id=re.compile("para$")) 
# [<p id="firstpara" align="center">This is paragraph <b>one</b>.</p>, 
# <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>] 

soup.findAll(attrs={'id' : re.compile("para$")}) 
# [<p id="firstpara" align="center">This is paragraph <b>one</b>.</p>, 
# <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>] 

,如果你需要把進口的屬性,其名稱是Python的保留字,像類的限制,或者您可以使用ATTRS;或名稱爲Beautiful Soup搜索方法的非關鍵字參數的屬性:名稱,遞歸,限制,文本或attrs本身。

from BeautifulSoup import BeautifulStoneSoup 
xml = '<person name="Bob"><parent rel="mother" name="Alice">' 
xmlSoup = BeautifulStoneSoup(xml) 

xmlSoup.findAll(name="Alice") 
# [] 

xmlSoup.findAll(attrs={"name" : "Alice"}) 
# [parent rel="mother" name="Alice"></parent>] 

因此,對於你給出的例子:

soup.findAll(attrs={ "foo" : re.compile(".*") }) 
# or 
soup.findAll(attrs={ re.compile("foo:.*") : re.compile(".*") }) 
+0

似乎並不當我運行它違揹我的示例工作。 – 2013-03-06 10:06:37

0

BeautifulSoup(包括版本3和4)不出現治療命名空間前綴什麼特別。它只將tho命名空間前綴和命名空間屬性視爲一個屬性,它的名稱中恰好有一個冒號。

因此,要找到與在foo命名空間屬性<p>元素,你就必須遍歷所有的屬性鍵和檢查attr.startswith('foo')

import BeautifulSoup as bs 
content = '''\ 
<p>blah</p> 
<p foo:bar="something">blah</p> 
<p foo:xxx="something">blah</p>''' 

soup = bs.BeautifulSoup(content) 
for p in soup.find_all('p'): 
    for attr in p.attrs.keys(): 
     if attr.startswith('foo'): 
      print(p) 
      break 

產生

<p foo:bar="something">blah</p> 
<p foo:xxx="something">blah</p> 

通過lxml您可以通過XPath進行搜索,XPath具有通過名稱空間搜索屬性的語法支持:

import lxml.etree as ET 
content = '''\ 
<root xmlns:foo="bar"> 
<p>blah</p> 
<p foo:bar="something">blah</p> 
<p foo:xxx="something">blah</p></root>''' 

root = ET.XML(content) 
for p in root.xpath('p[@foo:*]', namespaces={'foo':'bar'}): 
    print(ET.tostring(p)) 

產生

<p xmlns:foo="bar" foo:bar="something">blah</p> 
<p xmlns:foo="bar" foo:xxx="something">blah</p> 
+0

是否可以匹配屬性的開始,以便以foo開頭的任何屬性:?我編輯的問題。 – 2013-03-06 10:20:15