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

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

问题描述

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

电话 </th><th id="contact">否.<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">萨姆·斯里尼瓦斯·克里希那戈帕尔<td id="contact1">9894398690 </td><td id="contact1"></td></tr>
STUDENT IDNAME

我想要做的是将2011XXA4438F"提取为一个字符串,我该怎么做?

解决方案

first 标签,id 为 <代码>contact1".要获得它,您只需要soup.find:

<预><代码>>>>打印汤.find(id='contact1').text.strip()2011XXA4438F

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

<预><代码>>>>打印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>]

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>

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

解决方案

<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

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天全站免登陆