【问题标题】:Get all HTML tags with Beautiful Soup使用 Beautiful Soup 获取所有 HTML 标签
【发布时间】:2016-07-06 15:19:35
【问题描述】:

我正在尝试从美丽的汤中获取所有 html 标记的列表。

我看到 find all 但我必须知道标签的名称才能搜索。

如果有类似

的文字
html = """<div>something</div>
<div>something else</div>
<div class='magical'>hi there</div>
<p>ok</p>"""

我如何获得像

这样的列表
list_of_tags = ["<div>", "<div>", "<div class='magical'>", "<p>"]

我知道如何使用正则表达式来做到这一点,但我正在尝试学习 BS4

【问题讨论】:

标签: python html beautifulsoup


【解决方案1】:

您不必为find_all() 指定任何参数 - 在这种情况下,BeautifulSoup 会递归地找到树中的每个标签。示例:

>>> from bs4 import BeautifulSoup
>>>
>>> html = """<div>something</div>
... <div>something else</div>
... <div class='magical'>hi there</div>
... <p>ok</p>"""
>>> soup = BeautifulSoup(html, "html.parser")
>>> [tag.name for tag in soup.find_all()]
[u'div', u'div', u'div', u'p']
>>> [str(tag) for tag in soup.find_all()]
['<div>something</div>', '<div>something else</div>', '<div class="magical">hi there</div>', '<p>ok</p>']

【讨论】:

    【解决方案2】:

    请尝试以下方法--

    for tag in soup.findAll(True):
        print(tag.name)
    

    【讨论】:

      【解决方案3】:

      我想我会为以后发现自己在这里的人分享一个非常相似的问题的解决方案。

      示例

      我需要快速找到所有标签,但只需要唯一值。我将使用 Python calendar 模块进行演示。

      我们将生成一个 html 日历,然后对其进行解析,找到所有且仅存在的那些唯一标签。

      下面的结构非常类似于上面的,使用集合推导:

      >>> from bs4 import BeautifulSoup
      >>> import calendar
      >>>
      >>> html_cal = calendar.HTMLCalendar().formatmonth(2020, 1)
      >>> set(tag.name for tag in BeautifulSoup(html_cal, 'html.parser').find_all())
      {'table', 'td', 'th', 'tr'}
      

      【讨论】:

        【解决方案4】:

        如果你想找到一些特定的 HTML 标签,那么试试这个:

        html = driver.page_source
        soup = BeautifulSoup(html)
        for tag in soup.find_all(['a',’div’]):  # Mention HTML tag names here.
        print (tag.text)
        

        【讨论】:

          【解决方案5】:

          这是我用来解析不同 HTML 和文本文档的高效函数:

          def parse_docs(path, format, tags):
              """
              Parse the different files in path, having html or txt format, and extract the text content.
              Returns a list of strings, where every string is a text document content.
              :param path: str
              :param format: str
              :param tags: list
              :return: list
              """
          
              docs = []
              if format == "html":
                  for document in tqdm(get_list_of_files(path)):
                      # print(document)
                      soup = BeautifulSoup(open(document, encoding='utf-8').read())
                      text = '\n'.join([''.join(s.findAll(text=True)) for s in
                                        soup.findAll(tags)])  # parse all <p>, <div>, and <h> tags
                      docs.append(text)
              else:
                  for document in tqdm(get_list_of_files(path)):
                      text = open(document, encoding='utf-8').read()
                      docs.append(text)
              return docs
          

          一个简单的调用:parse_docs('/path/to/folder', 'html', ['p', 'h', 'div']) 将返回一个文本字符串列表。

          【讨论】:

            猜你喜欢
            • 2017-01-17
            • 2019-04-15
            • 2019-01-22
            • 1970-01-01
            • 1970-01-01
            • 2020-08-26
            • 2018-01-17
            • 2019-08-03
            相关资源
            最近更新 更多