python – BeautifulSoup创建一个标签
发布时间:2020-12-20 11:40:07 所属栏目:Python 来源:网络整理
导读:我需要创建一个 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 / ur
我需要创建一个< 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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |