gpt4 book ai didi

python - BeautifulSoup 创建一个 标签

转载 作者:太空狗 更新时间:2023-10-30 00:44:35 24 4
gpt4 key购买 nike

我需要创建一个 <img />标签。BeautifulSoup 使用我编写的代码创建了一个像这样的图像标签:

soup = BeautifulSoup(text, "html5")
tag = Tag(soup, name='img')
tag.attrs = {'src': '/some/url/here'}
text = soup.renderContents()
print text

输出:<img src="/some/url/here"></img>

如何制作? : <img src="/some/url/here" />

当然可以使用 REGEX 或类似的化学方法来完成。但是我想知道是否有任何标准方法可以生成这样的标签?

最佳答案

不要使用 Tag()创造新的元素。使用 soup.new_tag() method :

soup = BeautifulSoup(text, "html5")
new_tag = soup.new_tag('img', src='/some/url/here')
some_element.append(new_tag)

soup.new_tag()方法会将正确的构建器传递给 Tag()对象,它是负责识别 <img/> 的构建器作为空标签。

演示:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<div></div>', "html5")
>>> new_tag = soup.new_tag('img', src='/some/url/here')
>>> new_tag
<img src="/some/url/here"/>
>>> soup.div.append(new_tag)
>>> print soup.prettify()
<html>
<head>
</head>
<body>
<div>
<img src="/some/url/here"/>
</div>
</body>
</html>

关于python - BeautifulSoup 创建一个 <img/> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28030754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com