为了账号安全,请及时绑定邮箱和手机立即绑定

BeautifulSoup 使用类获取最近的标签,而不是兄弟姐妹并嵌套在未知兄弟姐妹中

BeautifulSoup 使用类获取最近的标签,而不是兄弟姐妹并嵌套在未知兄弟姐妹中

繁星coding 2021-10-19 17:08:22
<h3>    <span></span>    <span class='headline'>Headline #1</span></h3><table class='striped'></table><h4>    <span class='headline'>Headline #2</span></h4><table class='striped'></table><p>    <span class='headline'>Headline #3</span></p><ul></ul><center>    <table class='striped'></table></center>这是我的结构。我正在枚举表格标签,并希望使用最接近我的表格的“标题”类检索跨度标签的文本值。通过“最近”我的意思是,如果你要展平 html,我想用一个类“标题”来定位跨度,如果你从表格的点开始,你会首先遇到它有时这些跨度嵌套在 h3、有时是 h4、有时是 ap 标签中。有时 table 标签与 h3/h4/p 处于同一级别,有时它本身嵌套在 center 标签内。有时 h3/h4/p 标签是表的直接兄弟,有时不是。如何使用 BeautifulSoup 查找最近的 span.headline,无论嵌套级别如何以及它是否嵌套在父级或兄弟级中?到目前为止我有这个代码tables = soup.findAll("table", {"class": ["striped"]})for index, table in enumerate(tables):    headline = table.find_previous('h3').("span", {"class" : ["headline"]}).text
查看完整描述

1 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

我能够find_previous在每个表上使用该方法来查找您提供的示例 html 的前一个标题。idx在检查标题是否属于该表时,我为每个表添加了一个附加属性。我还在 html 的开头和结尾添加了两个没有以前标题的表格。


html = '''

<table class='striped'></table>

<h3>

    <span></span>

    <span class='headline'>Headline #1</span>

</h3>

<table class='striped'></table>

<h4>

    <span class='headline'>Headline #2</span>

</h4>

<table class='striped'></table>

<p>

    <span class='headline'>Headline #3</span>

</p>

<ul></ul>

<center>

    <table class='striped'></table>

</center>

<table class='striped'></table>

</div>

'''.replace('\n', '')


soup = BeautifulSoup(html, 'lxml')

table_query = ('table', {'class': 'striped'})

headline_query = ('span', {'class': 'headline'})


for idx, table in enumerate(soup.find_all(*table_query)):

    table.attrs['idx'] = idx

    previous_headline = table.find_previous(*headline_query)

    if (previous_headline and 

        previous_headline.find_next(*table_query).attrs['idx'] == idx):

        print(previous_headline.text)

    else:

        print('No headline found.')

输出:


No headline found.

Headline #1

Headline #2

Headline #3

No headline found.


查看完整回答
反对 回复 2021-10-19
  • 1 回答
  • 0 关注
  • 196 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信