使用th-tex导航表

2024-04-27 07:39:33 发布

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

我有下表:

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

我想在th下的td标签内找到文本,其中有“国籍”。我该怎么去那里?我用的是beauthulsoup和Python。在

还补充说,上面有很多th和td标记,以强调仅仅找到第一个th是不够的


Tags: andofinformationwithtable标签trclass
3条回答

如果您正在查看for the table本身,请考虑find_parent()

我修改了这个答案,因为你给出了一个你想要解析的特定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'

找到th标记,然后得到它的next sibling

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两次,因为第一次将给出换行符。在

相关问题 更多 >