【问题标题】:BS4 class with header tags带有标题标签的 BS4 类
【发布时间】:2020-01-01 17:38:34
【问题描述】:
如何解析一个类以仅获取标题标签之外的文本,或两者都在列表中?
<div class="footballMatchSummaryDef"><h1>Burnley v Aston Villa</h1>English Premier League at Turf Moor</div>
我曾考虑使用正则表达式提取,但认为美丽的汤一定不能处理它
【问题讨论】:
标签:
python
beautifulsoup
python-3.8
【解决方案1】:
有很多解决方案,一种是获取整个文本,然后根据一些分隔符将其拆分:
from bs4 import BeautifulSoup
txt = '''<div class="footballMatchSummaryDef"><h1>Burnley v Aston Villa</h1>English Premier League at Turf Moor</div>'''
soup = BeautifulSoup(txt, 'html.parser')
lst = soup.select_one('.footballMatchSummaryDef').get_text(separator='|').split('|')
print(lst)
打印:
['Burnley v Aston Villa', 'English Premier League at Turf Moor']
或者使用bs4导航功能:
print( soup.h1.text )
print( soup.h1.find_next_sibling(text=True) )
打印:
Burnley v Aston Villa
English Premier League at Turf Moor
【解决方案2】:
感谢 Andrej,导航功能是我所追求的,工作正常,只是刚刚启动 python,所以我从 php 开始对我来说是全新的。这是我需要的下一个兄弟姐妹
print( soup.h1.find_next_sibling(text=True) )