无法提取所需的文本部分并从某些元素中删除其余部分

时间:2017-12-26 11:47:39

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

我在我的python代码中使用了一个选择器从Soccer: Next To Play中获取html elements。当我使用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

1 个答案:

答案 0 :(得分: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