2012-04-16 34 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