【问题标题】:Find unknown tag containing given text查找包含给定文本的未知标签
【发布时间】:2020-12-25 23:31:53
【问题描述】:

我的 HTML 是这样的:

<body>
  <div class="afds">
    <span class="dfsdf">mytext</span>
  </div>
  <div class="sdf dzf">
    <h1>some random text</h1>
  </div>
</body>

我想查找所有包含“text”的标签及其对应的类。在这种情况下,我想要:

  • 跨度,“dfsdf”
  • h1,空

接下来,我希望能够浏览返回的标签。例如,找到所有返回的标签的div父标签和各自的类。

如果我执行以下操作

soupx.find_all(text=re.compile(".*text.*"))

它只是返回标签的文本部分:

['mytext', ' some random text']

请帮忙。

【问题讨论】:

    标签: python html beautifulsoup html-parsing


    【解决方案1】:

    您可能正在寻找以下方面的内容:

    ts = soup.find_all(text=re.compile(".*text.*"))
    for t in ts:
        if len(t.parent.attrs)>0:
            for k in t.parent.attrs.keys():
                print(t.parent.name,t.parent.attrs[k][0])
        else:
            print(t.parent.name,"null")
    

    输出:

    span dfsdf
    h1 null
    

    【讨论】:

      【解决方案2】:

      find_all() 不只返回字符串,它返回bs4.element.NavigableString。 这意味着您可以对这些结果调用其他 beautifulsoup 函数。

      看看 find_parent 和 find_parents:documentation

      childs = soupx.find_all(text=re.compile(".*text.*"))
      for c in childs:
          c.find_parent("div")
      

      【讨论】:

        猜你喜欢
        • 2011-09-03
        • 2014-06-01
        • 2010-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-09
        • 1970-01-01
        • 2017-01-24
        相关资源
        最近更新 更多