仅在Beautifulsoup中的特定跨度内容之后获取表内容

2024-04-30 03:20:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个html文件,有几个div,没有类名或id名:

<div><span>Item 1</span></div>
<div>some content</div>
<div><table><tbody>table content</tbody></table></div>

<div><span>Item 2</span></div>
<div>some content</div>
<div><table><tbody>table content</tbody></table></div>

<div><span>Item 3</span></div>
<div>some content</div>
<div><table><tbody>table content</tbody></table></div>

<div><span>Item 4</span></div>
<div>some content</div>
<div><table><tbody>table content</tbody></table></div>

目标:
我只想在项目3之后提取表格的内容,并进行常规搜索,以获取特定项目编号之后的任何表格。请注意,物品的数量可能会有所不同

已尝试:
我尝试了以下代码:

if soup.find('span') == 'Item 3. Selected Financial Data':
    table_tag = soup.find('tbody')

但它仍然从顶部返回第一个表

我也试过看.next_兄弟姐妹和.next_元素,但没有更好的方法来实现这一点吗? https://www.crummy.com/software/BeautifulSoup/bs4/doc/#going-sideways

这里有一个类似的问题:get text after specific tag with beautiful soup,但它不涉及div中的表

请帮忙


1条回答
网友
1楼 · 发布于 2024-04-30 03:20:13

只需使用find_all_next

table = soup.find(text='Item 3').find_all_previous()[2].find_all_next()

我的完整代码:

from bs4 import BeautifulSoup

html = '''
<div><span>Item 1</span></div>
<div>some content</div>
<div><table><tbody>table content</tbody></table></div>

<div><span>Item 2</span></div>
<div>some content</div>
<div><table><tbody>table content</tbody></table></div>

<div><span>Item 3</span></div>
<div>some content</div>
<div><table><tbody>table content</tbody></table></div>

<div><span>Item 4</span></div>
<div>some content</div>
<div><table><tbody>table content</tbody></table></div>
'''

soup = BeautifulSoup(html,'html5lib')

table = soup.find(text='Item 3').find_all_previous()[2].find_all_next()

table_html = ''.join([str(elem) for elem in table])

输出:

>>> table
[<div><span>Item 3</span></div>, <span>Item 3</span>, <div>some content</div>, <div>table content<table><tbody></tbody></table></div>, <table><tbody></tbody></table>, <tbody></tbody>, <div><span>Item 4</span></div>, <span>Item 4</span>, <div>some content</div>, <div>table content<table><tbody></tbody></table></div>, <table><tbody></tbody></table>, <tbody></tbody>]

>>> table_html
'<div><span>Item 3</span></div><span>Item 3</span><div>some content</div><div>table content<table><tbody></tbody></table></div><table><tbody></tbody></table><tbody></tbody><div><span>Item 4</span></div><span>Item 4</span><div>some content</div><div>table content<table><tbody></tbody></table></div><table><tbody></tbody></table><tbody></tbody>'

相关问题 更多 >