BeautifulSoup - adding attribute to tag

前端 未结 1 590
春和景丽
春和景丽 2020-12-16 14:48

Question for you here, I\'m trying to add an attribute to a tag here, wondering if I can use a BeautifulSoup method, or should use plain string manipulation.

An exam

相关标签:
1条回答
  • 2020-12-16 15:32

    Easy with BeautifulSoup :)

    >>> from bs4 import BeautifulSoup
    >>> soup = BeautifulSoup('<option value="BC">BRITISH COLUMBIA</option>')
    >>> soup.find('option')['selected'] = ''
    >>> print soup
    <html><body><option selected="" value="BC">BRITISH COLUMBIA</option></body></html>
    

    The attributes can be looked at as a dictionary. So we have {'value':'BC'}, and to add a value to a dictionary, we just do dict[key] = value

    0 讨论(0)
提交回复
热议问题