python beautifulsoup new_tag:将类指定为属性

Ant*_*gor 7 python beautifulsoup

我是python和beautifulsoup的新手,所以也许有一个我找不到的简单答案.

当我打电话的时候.new_tag('name')我也可以分配属性.new_tag('a', href='#', id='link1')

但我不能这样分配类,因为它是保留字.此外,我无法以这种方式添加名称,因为它用作标记名称属性的关键字.我知道我可以稍后添加它们,tag['class']例如,但我想知道,这是将类添加到新标记的唯一方法吗?或者有一种方法可以一步到位吗?

ita*_*tai 22

你是对的 - class是一个python保留字,不能用作关键字参数,因为语言解析器会抱怨.

有一种解决方法 - 您可以通过前面的字典给出函数关键字参数**.这样"class"只是另一个字符串,在解析python语法时不会与保留字冲突,但关键字参数在运行时正确传递.

在您的情况下,解决方法应该是 -

soup.new_tag('a', href='#', id='link1', **{'class':'classname'})
Run Code Online (Sandbox Code Playgroud)

我知道有点丑,但它有效..;)

  • 是的,这有效!可能是我对python的了解太差了,但是我已经尝试过类似的方法,但是失败了。你的代码运行得很好。谢谢你! (2认同)

小智 6

您可以使用 attrs 词典:

soup.new_tag("a",attrs={"class": "classname", "href" : "#", "id" : "link1"})
Run Code Online (Sandbox Code Playgroud)

结果将是:

<a class="classname" href="#" id="link1"></a>    
Run Code Online (Sandbox Code Playgroud)