Rob Carr
Rob Carr

Reputation: 270

Dynamically specifying tags while using replaceWith in Beautiful Soup

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.

Upvotes: 0

Views: 598

Answers (2)

nosklo
nosklo

Reputation: 223172

No need to use getattr:

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

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 882851

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!

Upvotes: 2

Related Questions