views:

195

answers:

2

Previously I asked this question and got back this BeautifulSoup example code, which after some consultation locally, I decided to go with.

>>> from BeautifulSoup import BeautifulStoneSoup
>>> html = """
... <config>
... <links>
... <link name="Link1" id="1">
...  <encapsulation>
...   <mode>ipsec</mode>
...  </encapsulation>
... </link>
... <link name="Link2" id="2">
...  <encapsulation>
...   <mode>udp</mode>
...  </encapsulation>
... </link>
... </links>
... </config>
... """
>>> soup = BeautifulStoneSoup(html)
>>> soup.find('link', id=1)
<link name="Link1" id="1">
<encapsulation>
<mode>ipsec</mode>
</encapsulation>
</link>
>>> soup.find('link', id=1).mode.contents[0].replaceWith('whatever')
>>> soup.find('link', id=1)
<link name="Link1" id="1">
<encapsulation>
<mode>whatever</mode>
</encapsulation>
</link>

The only problem with this is that the example has a hardcoded tag value (in this case "mode"), and I need to be able to specify any tag within the specified "link" tag. Simple variable substitution doesn't seem to work.

+2  A: 

Try getattr(soup.find('link', id=1), sometag) where you now have a hardcoded tag in soup.find('link', id=1).mode -- getattr is the Python way to get an attribute whose name is held as a string variable, after all!

Alex Martelli
Thank you. That works.
Rob Carr
A: 

No need to use getattr:

sometag = 'mode'
result = soup.find('link', id=1).find(sometag)
print result
nosklo