【问题标题】:Beautiful Soup get nested span by class within another spanBeautiful Soup 在另一个跨度内按类嵌套跨度
【发布时间】:2022-12-05 01:23:21
【问题描述】:

在一个非常大的 HTML 页面中,我想通过 class 获得一个 span,这是唯一的。这孩子这个的span,也可以通过class查询,但是哪个是不是唯一的.

...
<span class="uniqueParent">
   <span class="notUniqueChildClassName">
      I am the child
   </span>
</span> 
...

输出应该是“我是孩子”。

我努力了:

s = soup.select('span[class="uniqueParent"] > span[class="notUniqueChildClassName"]')
s.text

s = soup.find('span[class="uniqueParent"] > span[class="notUniqueChildClassName"]')
s.text

但是两者都没有用。

【问题讨论】:

    标签: beautifulsoup


    【解决方案1】:

    尝试将第一次尝试更改为

    soup.select_one('span[class="uniqueParent"] > span[class="notUniqueChildClassName"]').text.strip()
    

    在您的实际 html 上。

    输出应该是你正在寻找的。

    【讨论】:

      【解决方案2】:

      您可以使用带点的 CSS 选择器(例如 .uniqueParent,而不是 class="uniqueParent"):

      from bs4 import BeautifulSoup
      
      
      html_doc = """
      <span class="uniqueParent">
         <span class="notUniqueChildClassName">
            I am the child
         </span>
      </span> """
      
      
      soup = BeautifulSoup(html_doc, "html.parser")
      
      print(soup.select_one(".uniqueParent .notUniqueChildClassName").text)
      

      印刷:

      
            I am the child
         
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-21
        • 1970-01-01
        • 2021-03-28
        • 2018-03-15
        • 2021-12-30
        • 2021-07-02
        • 2020-01-30
        相关资源
        最近更新 更多