BeautifulSoup创建一个<img/>标签

时间:2015-01-19 17:54:41

标签: python html parsing tags beautifulsoup

我需要创建一个<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或类似的化学方法完成。但是我想知道是否有任何标准方法可以生成这样的标签?

1 个答案:

答案 0 :(得分:8)

不要使用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>
相关问题