选择一个特定列并忽略BeautifulSoup Python中的其余列(避免嵌套表)



我正试图使用python中的beautifulsoup只获取网页表的前两列。问题是,该表有时在第三列中包含嵌套表。html的结构类似于此:

<table class:"relative-table wrapped">
<tbody>
<tr>
<td>
<td>
<td>
<td>
<td>
<td>
<tr>
<tr>
<td>
<td>
<td>
<td>
<td>
<div class="table-wrap">
<table class="relative-table wrapped">
...
...
<table>
<div>
<td>
<tr>
<tbody>
<table>

主要的问题是,我不知道如何简单地忽略每三个td,这样我就不会读取主表中的嵌套表。我只想有一个主表第一列的列表和另一个主表格第二列的列表,但当我阅读时,嵌套的表格会破坏一切。我尝试过这个代码:

import requests
from bs4 import BeautifulSoup
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
links = soup.select("table.relative-table tbody tr td.confluenceTd")
anchorList = []
for anchor in links:
anchorList.append(anchor.text)
del anchorList[2:len(anchorList):3]
for anchorItem in anchorList:
print(anchorItem)
print('-------------------')

这非常有效,直到我到达嵌套表,然后它开始删除其他列。我也尝试过其他代码:

page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
for row in soup.findAll('table')[0].tbody.findAll('tr'):
firstColumn = row.findAll('td')[0].contents
secondColumn = row.findAll('td')[1].contents
print(firstColumn, secondColumn)

但我得到了一个IndexError,因为它正在读取嵌套的选项卡,而嵌套的表只有一个td

有人知道我怎么能读前两列而忽略其余的吗?

谢谢。

可能需要一些改进的示例/细节来澄清,但据我所知,您正在选择第一个<table>并尝试迭代其行:

soup.table.select('tr:not(:has(table))')

上面的选择器将排除所有包含额外<table>的thr行。

替代方案是去掉最后/第三个<td>:

for row in soup.table.select('tr'):
row.select_one('td:last-of-type').decompose()
#### or by its index row.select_one('td:nth-of-type(3)').decompose()

现在,您可以在具有两列的<table>上执行您的选择。

示例

from bs4 import BeautifulSoup
html ='''
<table class:"relative-table wrapped">
<tbody>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
<div class="table-wrap">
<table class="relative-table wrapped">
...
...
</table>
</div>
</td>
</tr>
</tbody>
</table>
'''
soup = BeautifulSoup(html, 'html.parser')
for row in soup.table.select('tr'):
row.select_one('td:last-of-type').decompose()
soup

新汤

<table class:"relative-table="" wrapped"="">
<tbody>
<tr>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
</tr>
</tbody>
</table>

最新更新