使用BeautifulSoup添加元标记

sud*_*810 1 python beautifulsoup python-2.7

如何使用Beautiful Soup(库)在HTML页面中的标题标记之后添加元标记.我使用python语言进行编码,但无法执行此操作.

Mar*_*ers 7

使用soup.create_tag()创建一个新的<meta>标签,设置该属性并将其添加到您的文档<head>.

metatag = soup.new_tag('meta')
metatag.attrs['http-equiv'] = 'Content-Type'
metatag.attrs['content'] = 'text/html'
soup.head.append(metatag)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''\
... <html><head><title>Hello World!</title>
... </head><body>Foo bar</body></html>
... ''')
>>> metatag = soup.new_tag('meta')
>>> metatag.attrs['http-equiv'] = 'Content-Type'
>>> metatag.attrs['content'] = 'text/html'
>>> soup.head.append(metatag)
>>> print soup.prettify()
<html>
 <head>
  <title>
   Hello World!
  </title>
  <meta content="text/html" http-equiv="Content-Type"/>
 </head>
 <body>
  Foo bar
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)