【问题标题】:Add meta tag using BeautifulSoup使用 BeautifulSoup 添加元标记
【发布时间】:2014-05-30 21:50:48
【问题描述】:

如何使用 Beautiful Soup(library) 在 HTML 页面中的标题标签之后添加元标签。我正在使用 python 语言进行编码,但无法做到这一点。

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案1】:

    使用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)
    

    演示:

    >>> 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>
    

    【讨论】:

    • ya 它正常工作正常关键字。但是有些内容是不可能添加到元标记中的。它会产生编码错误。我尝试过 .encode('UTC-8') 来解决问题,但无法解决。
    • 插入新数据时使用Unicode字符串;任何 encode 错误都是由于 I/O 错误(将 Unicode 打印到无法处理它的终端或无法处理它的文件等)。
    • 你能给我举个例子吗?
    • 我已经在我的帖子中给出了一个关于如何添加元标记的示例。它适用于 Unicode 字符串。有很多方法可以在 Python 中触发 Unicode 编码或解码异常,我的一个示例不会向您展示如何避免 在代码中看到的异常。也许您需要针对该特定问题发布一个新问题;确保在此类问题中包含可重现的代码示例。
    猜你喜欢
    • 2013-05-29
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 2020-08-20
    • 2011-10-27
    相关资源
    最近更新 更多