【问题标题】:BeautifulSoup create a <img /> tagBeautifulSoup 创建一个 <img /> 标签
【发布时间】:2015-03-17 19:40:53
【问题描述】:

我需要创建一个&lt;img /&gt; 标签。 BeautifulSoup 用我做的代码创建了一个这样的图像标签:

soup = BeautifulSoup(text, "html5")
tag = Tag(soup, name='img')
tag.attrs = {'src': '/some/url/here'}
text = soup.renderContents()
print text

输出:&lt;img src="/some/url/here"&gt;&lt;/img&gt;

如何制作? :&lt;img src="/some/url/here" /&gt;

当然可以使用 REGEX 或类似的化学方法来完成。但是我想知道是否有任何标准方法可以生成这样的标签?

【问题讨论】:

    标签: python html parsing tags beautifulsoup


    【解决方案1】:

    不要使用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() 对象,它是负责将&lt;img/&gt; 识别为空标记的构建器。

    演示:

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

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 2011-02-26
      • 2012-04-17
      • 2021-05-16
      • 2018-01-07
      • 2021-08-01
      • 1970-01-01
      • 2019-05-11
      • 2013-01-11
      相关资源
      最近更新 更多