Dynamic tagging when using replaceWith in Beautiful Soup

I used to ask this question and return this BeautifulSoup code example which after some local consultation 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 is that the example has a hard tag meaning (in this case "mode") and I need to specify any tag in the specified "link" tag. Simple variable substitution doesn't work.

0


a source to share


2 answers


Try getattr(soup.find('link', id=1), sometag)

where you now have a hardcoded tag in soup.find('link', id=1).mode

- getattr

this is the Python way of getting an attribute whose name is stored as a string variable!



+2


a source


Don't need to use getattr

:



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

      

0


a source







All Articles