【问题标题】:List of all element names in HTML document — beautifulsoupHTML 文档中所有元素名称的列表——beautifulsoup
【发布时间】:2016-11-11 07:15:12
【问题描述】:

我想获得一个包含 HTML 文档的所有不同标记名称的列表(不重复的标记名称字符串列表)。我尝试使用soup.findall() 输入空条目,但这却给了我整个文档。

有办法吗?

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    使用soup.findall(),您可以获得可以迭代的每个元素的列表。因此,您可以执行以下操作:

    from bs4 import BeautifulSoup
    
    html_doc = """
    <html><head><title>The Dormouse's story</title></head>
    <body>
    <p class="title"><b>The Dormouse's story</b></p>
    
    <p class="story">Once upon a time there were three little sisters; and their names were
    <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
    <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
    and they lived at the bottom of a well.</p>
    
    <p class="story">...</p>
    """  # an html sample
    soup = BeautifulSoup(html_doc, 'html.parser')
    
    document = soup.html.find_all()
    
    el = ['html',]  # we already include the html tag
    for n in document:
        if n.name not in el:
            el.append(n.name)
    
    print(el)
    


    代码 sn-p 的输出将是:

    >>> ['head', 'title', 'body', 'p', 'b', 'a']
    


    编辑

    正如@PM 2Ring 指出的那样,如果您不关心添加元素的顺序(正如他所说,我认为不是这种情况),那么您可以使用集合。在 Python 3.x 中您不必导入它,但如果您使用旧版本,您可能需要检查它是否受支持。

    from bs4 import BeautifulSoup
    
    ...
    
    el = {x.name for x in document} # use a set comprehension to generate it easily
    el.add("html")  # only if you need to
    

    【讨论】:

    • 简单明了。好动。我想它也适用于标题标签,不是吗?
    • 顺便说一句,您缺少其中的 html 标记。
    • @wonderwhy - 已编辑。现在它也包括在内。是的,它还遍历 &lt;head&gt; 标记。输出将是:['html', 'head', 'title', 'body', 'p', 'b', 'a']
    • el 使用集合而不是列表会很多更有效,因为您无需费心进行in 测试。当然,集合不会保持顺序,但这在这里可能不是问题。如果 OP 真的需要一个列表,那么在最后将集合转换为列表很容易。
    • @firelitte 首先将 URL 放入字符串标签中。
    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 2012-02-21
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多