在文本之后搜索BeautifulSoup,需要从表行中获取所有数据

时间:2018-06-07 12:58:03

标签: python 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多行,格式相同。我想要做的是搜索long 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,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

一种方法是使用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 )