开发者

How do I insert an attribute using BeautifulSoup?

How do I insert an attribute using BeautifulSoup?

For example, insert border="1" as a <table> tag attribute.

EDIT:

I've answered my own question (for a particular class of table, 开发者_运维问答even):

inTopic = urllib2.urlopen("file:///C:/test/test.html")
content = BeautifulSoup(inTopic)

tlist = content.findAll('table', "myTableClass")
for tbl in tlist:
    tbl['border'] = "1"
    print tbl.attrs


How about:

inTopic = urllib2.urlopen('http://stackoverflow.com/questions/4951331/how-do-i-insert-an-attribute-using-beautifulsoup')
content = BeautifulSoup.BeautifulSoup(inTopic)
tlist = content.findAll('table')
for tbl in tlist:
    tbl.attrs.append(('border', 1))

Do not forget to try lxml.html, it's fast and parse well.


with node.attrs['myNewAttr'] = 'my_new_value' for example:

content = BeautifulSoup(text, 'html.parser')
links = content.findAll('a') 
for node in links:
    node.attrs['myNewAttr'] = 'my_new_value'

in this case:

<ul>
   <li><a>text</a</li>
   <li><a>text</a</li>
</ul>

will return

<ul>
   <li><a myNewAttr="my_new_value">text</a</li>
   <li><a myNewAttr="my_new_value">text</a</li>
</ul>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜