2012-04-16 31 views
0

使用beautifulsoup 4,如何根據名稱編輯值?鑑於我知道name =「foo」(常量和唯一),我如何讀取值「bar」(運行時未知),並將其更改爲新字符串「baz」?根據密鑰編輯XML值

我可以使用soup.find_all(文=「富」)讀取行,但我無法弄清楚如何方便地讀取該值,或更改字符串「bar」 - >「巴茲」

XML摘錄:

<djmacros> 
    <macro name="foo" value="bar"> 
    <description>foobar</description> 
    </macro> 
</djmacros> 

回答

1

我還沒有嘗試過,但我會懷疑這樣的事情可能工作:

foo_element = soup.find('macro', attrs={"name" : "foo"}) # returns the foo element 
foo_element['value'] = "baz" # changes the value attribute 
+0

那完美。非常感謝! – moreisee 2012-04-16 23:10:11