【问题标题】:get text from element using css selector excluding text inside nested element使用css选择器从元素中获取文本,不包括嵌套元素内的文本
【发布时间】:2021-06-03 07:28:54
【问题描述】:

我需要使用 css 选择器从 span 中获取文本,但不包括 sup 中的文本:

<span>(6-4, 7-6<sup>4</sup>)</span>

我试过这个 css 选择器但没有用:

span :not(sup)
# soup.select_one('span :not(sup)').text

我需要的结果是这样的: "(6-4, 7-6)"

【问题讨论】:

    标签: python css web-scraping beautifulsoup css-selectors


    【解决方案1】:

    试试这个,只获取父元素的文本,排除所有子元素的文本。

    span_element = soup.find('span')
    span_text = span_element.find(text=True, recursive=False)
    

    输出: 6-4, 7-6

    【讨论】:

      【解决方案2】:

      使用 BeautifulSoup,您可以使用find_next() 方法:

      print(soup.select_one('span').find_next(text=True))
      

      【讨论】:

        猜你喜欢
        • 2022-12-12
        • 1970-01-01
        • 1970-01-01
        • 2015-02-16
        • 2020-04-21
        • 1970-01-01
        • 1970-01-01
        • 2021-09-04
        • 2012-09-01
        相关资源
        最近更新 更多