使用文本导航表



我有以下表格:

<table class="information">
  <tr> .... lots of rows with <th> and <td></tr>
  <tr>
   <th>Nationality</th>
   <td><a href="..">Stackoverflowian</a></td>
  </tr>
</table>

我想找到文本在td标签在th下的"国籍"。我该如何在那里导航?我用的是Beautifulsoup和Python。

添加了很多th和td标签,强调仅仅找到

是不够的。

找到th标签,然后找到它的下一个兄弟:

soup = BeautifulSoup(html)
ths = soup.find_all('th')
for th in ths:
    if th.text == "Nationality":
        print th.next_sibling.next_sibling.text
# Stackoverflowian

我们需要执行两次next_sibling,因为第一次将给出换行符

我已经修改了这个答案,因为你给了一个特定的HTML页面,你试图解析。

r = requests.get("http://https://en.wikipedia.org/wiki/Usain_Bolt")
# test that we loaded the page successfully!
soup = BeautifulSoup(r.text, "html.parser")
thTag = soup.find('th', text='Nationality'):
tdTag = thTag.next_sibling.next_sibling
print(tdTag.text)
>>>'Jamaican'

如果您正在寻找表本身,那么考虑find_parent()

最新更新