python beautifulsoup new_tag:将类分配为属性 [英] python beautifulsoup new_tag: assign class as an attribute
问题描述
我是python和beautifulsoup的新手,所以也许我找不到一个简单的答案.
I'm new to both python and beautifulsoup, so maybe there is a simple answer I can't find.
当我呼叫.new_tag('name')
时,我还可以分配诸如.new_tag('a', href='#', id='link1')
When I call .new_tag('name')
I also can assign attributes like .new_tag('a', href='#', id='link1')
但是我不能以这种方式分配类,因为它是保留字.同样,我也不能以这种方式添加名称,因为它被用作标签名称属性的关键字.我知道以后可以添加它们,例如使用tag['class']
,但是我想知道,这是将类添加到新标签的唯一方法吗?还是有一个步骤可以做到这一点?
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?
推荐答案
您是对的-class是python保留的单词,由于语言解析器会抱怨,因此不能用作关键字参数.
You are right - class is a python reserved word and cannot be used as a keyword argument because the language parser complains.
有一种解决方法-您可以通过以**
开头的字典为function关键字参数赋值.
这样,类"只是另一个字符串,在解析python语法时不会与保留字冲突,但是关键字参数会在运行时正确传递.
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.
您的解决方法应为-
soup.new_tag('a', href='#', id='link1', **{'class':'classname'})
我知道有些丑陋,但它可以工作..;)
Kind of ugly I know but it works.. ;)
这篇关于python beautifulsoup new_tag:将类分配为属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!