首页 > 解决方案 > 在文本后搜索 BeautifulSoup,需要从表行中获取所有数据

问题描述

我有一张这样的桌子:

<table id="test" class="tablesorter">
<tr class="even">
  <td style="background: #F5645C; color: #F5645C;">1&#160;</td>
  <td>Major Lazer</td>
  <td class="right">64</td>
  <td>93.1.15.107</td>
  <td>0x0110000105DAB310</td>
  <td class="center">No</td>
  <td class="center">No</td>
</tr>

<tr class="odd">
  <td style="background: #8FB9B0; color: #8FB9B0;">0&#160;</td>
  <td>Michael gunin</td>
  <td class="right">64</td>
  <td>57.48.41.27</td>
  <td>0x0110000631HDA213</td>
  <td class="center">No</td>
  <td class="center">No</td>
</tr>

...

</table>

该表有 100 多行,格式相同。我要做的是在长id之后搜索,然后找到那个表行并获取IP和名称。

例如,搜索:0x0110000105DAB310 然后找到该文本所在的特定表格行,并获取其余信息,例如:Major Lazer 和 93.1.15.107

table = playerssoup.find('table')
table_rows = table.find_all('tr')
for tr in table_rows:
  td = tr.find('td', text='0x0110000101517CC6')

这向我展示了 td,但我不知道从这里该怎么做。

标签: pythonbeautifulsoup

解决方案


一种方法是使用find_previous_sibling('td')

前任:

for tr in table_rows:
    td = tr.find('td', text='0x0110000105DAB310')
    if td is not None:
        print( td.find_previous_sibling('td').text )
        print( td.find_previous_sibling('td').find_previous_sibling('td').find_previous_sibling('td').text )

推荐阅读