python beautifulsoup new_tag: assign class as an attribute

眉间皱痕 提交于 2020-01-03 08:39:12

问题


I'm new to both python and beautifulsoup, so maybe there is a simple answer I can't find.

When I call .new_tag('name') I also can assign attributes like .new_tag('a', href='#', id='link1')

But I can't assign class this way, because it is reserved word. Also I can't add name this way, because it's used as keyword for the tag name attribute. I know I can add them later, using tag['class'] for example, but I would like to know, is this the only way to add class to new tag? Or there is a way to do that with a single step?


回答1:


You are right - class is a python reserved word and cannot be used as a keyword argument because the language parser complains.

There's a way around this - you can give the function keyword arguments through a dictionary preceded by **. That way "class" is just another string and wont collide with the reserved word when the python syntax is parsed, but the keyword argument gets passed correctly at runtime.

In your case the workaround should be -

soup.new_tag('a', href='#', id='link1', **{'class':'classname'})

Kind of ugly I know but it works.. ;)




回答2:


You can use the attrs dictionnary:

soup.new_tag("a",attrs={"class": "classname", "href" : "#", "id" : "link1"})

The result will be:

<a class="classname" href="#" id="link1"></a>    


来源:https://stackoverflow.com/questions/23042963/python-beautifulsoup-new-tag-assign-class-as-an-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!