我需要创建一个<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或类似的化学方法来完成。然而,我想知道是否有任何标准的方法来产生这样的标签?
发布于 2015-01-19 18:03:14
不要使用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>发布于 2022-01-29 16:51:52
在BS4中,您也可以这样做:
img = BeautifulSoup('<img src="/some/url/here" />', 'lxml').img
print(img)
print(type(img))将产生以下结果:
<img src="/some/url/here"/>
<class 'bs4.element.Tag'>https://stackoverflow.com/questions/28030754
复制相似问题