我将如何解析一个类以仅获取标题标记之外的文本,或两者都在列表中?
<div class="footballMatchSummaryDef"><h1>Burnley v Aston Villa</h1>English Premier League at Turf Moor</div>
我考虑过使用正则表达式来提取,但认为漂亮的汤一定无法处理
我将如何解析一个类以仅获取标题标记之外的文本,或两者都在列表中?
<div class="footballMatchSummaryDef"><h1>Burnley v Aston Villa</h1>English Premier League at Turf Moor</div>
我考虑过使用正则表达式来提取,但认为漂亮的汤一定无法处理
有很多解决方案,一种是获取整个文本,然后根据一些分隔符将其拆分:
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
感谢 Andrej,导航功能是我所追求的,工作正常,只是刚刚启动 python,所以从 php 对我来说都是新的。这是我需要的下一个兄弟姐妹
print( soup.h1.find_next_sibling(text=True) )