【问题标题】:Unable to extract a desired portion of text and discard the rest out of some elements无法提取所需的文本部分并从某些元素中丢弃其余部分
【发布时间】:2018-06-07 06:34:54
【问题描述】:

我在我的 python 代码中使用了一个选择器来从一些html elements 中获取Soccer: Next To Play。当我使用 for loop.extract() 不需要的部分时,它工作正常。但是,除了我在下面所做的之外,还有什么更好的方法可以将上述文本从元素中提取出来,或者至少使用单行表达式来做同样的事情。

from bs4 import BeautifulSoup

content='''
  <div class="page-title-new">
   <h1>
    Soccer: Next To Play
    <span aria-hidden="true" class="race-large ng-hide" ng-show="vm.hasRaceNumber()">
     RACE
    </span>
    <span aria-hidden="true" class="race-small ng-hide" ng-show="vm.hasRaceNumber()">
     R
    </span>
    <span aria-hidden="true" class="ng-hide" ng-show="vm.hasRaceNumber()">
    </span>
   </h1>
   <div aria-hidden="true" class="page-info-new ng-hide" ng-show="vm.hasEventDetailItems()">
    <!-- -->
   </div>
  </div>
'''

soup = BeautifulSoup(content,"lxml")
for item in soup.select(".page-title-new h1"):
    for elem in item.select("span"):elem.extract()
    print(item.text.strip())

# items = [item.text for item in soup.select(".page-title-new h1")] #what to do to finish it as a one-liner
# print(items)

有了循环,我得到了什么(这是我希望没有循环或单行代码得到的):

Soccer: Next To Play

没有循环我得到什么:

Soccer: Next To Play RACE R

【问题讨论】:

    标签: python python-3.x beautifulsoup css-selectors


    【解决方案1】:

    使用soup.select_one() 方法(仅查找与 CSS 选择器匹配的第一个标签):

    ...
    soup = BeautifulSoup(content,"lxml")
    result = soup.select_one(".page-title-new > h1").contents[0].strip()
    
    print(result)
    

    输出:

    Soccer: Next To Play
    

    【讨论】:

    • 你是这样的宝石@RomanPerekhrest。它工作得非常完美。您能否提供任何指向contents 用法的链接,以便我了解更多信息。谢谢。
    • @Topto,不客气。见链接crummy.com/software/BeautifulSoup/bs4/doc/…
    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多