在Python中使用BeautifulSoup找到一个html标签 [英] Find a html tag using BeautifulSoup in Python

查看:183
本文介绍了在Python中使用BeautifulSoup找到一个html标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在html代码中找到一个特定的标签,如果有2个标签,那么如何获取第二个标签的内容,而不是第一个这样的一个,这里是soup.find(id ='contact1')示例html代码

I want to find a specific tag in a html code like if there are 2 tags then how can i get the contents of the second tag and not the first one which soup.find(id='contact1') does here is the example html code

<table align="center"><th id="contact">STUDENT ID</th><th id="contact">NAME</th><th id="contact">   Phone </th><th id="contact"> NO.</th>
<p align="center" style="display:compact; font-size:18px; font-family:Arial, Helvetica, sans-serif; color:#CC3300">
</p><tr>
<td id="contact1">
2011XXA4438F </td> <td id="contact1"> SAM SRINIVAS KRISHNAGOPAL</td> <td id="contact1"> 9894398690 </td> <td id="contact1"> </td>
</tr>
</table>

我想做的是将2011XXA4438F作为字符串提取,我该怎么做? / p>

What i want to do is to extract '2011XXA4438F' as a string how can i do this?

推荐答案

< td id =contact1> em>第一个标签,ID为contact1。要获得它,那么 soup.find 是你需要的:

<td id="contact1"> is the first tag with an id of "contact1". To obtain it, then soup.find is all you need:

>>> print soup.find(id='contact1').text.strip()
2011XXA4438F

如果您正在寻找其他标签,那么您将需要使用 find_all

If you're looking for other tags, then you'll want to use find_all:

>>> print soup.find_all(id='contact1')
[<td id="contact1">
2011XXA4438F </td>, <td id="contact1"> SAM SRINIVAS KRISHNAGOPAL</td>, <td id="contact1"> 9894398690 </td>, <td id="contact1"> </td>]

这篇关于在Python中使用BeautifulSoup找到一个html标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆