获取一个标签之外和另一个标签内的文本

时间:2011-08-25 16:08:44

标签: python html-parsing beautifulsoup

我正在使用BeautifulSoup解析一个网页,它有一些如下所示的元素:

<td><font size="2" color="#00009c"><b>Consultant Registration Number  :</b></font>  16043646</td>

结构似乎总是<td>,第一部分被<font><b>包围,</font>标记后面的文字可能为空。如何获取字体标记之后的文本?

在这个例子中,我希望获得"16043646"。如果html是

<td><font size="2" color="#00009c"><b>Consultant Registration Number  :</b></font></td>

我想要""

1 个答案:

答案 0 :(得分:5)

>>> from BeautifulSoup import BeautifulSoup
>>> text1 = '<td><font size="2" color="#00009c"><b>Consultant Registration Number  :</b></font>  16043646</td>'
>>> text2 = '<td><font size="2" color="#00009c"><b>Consultant Registration Number  :</b></font></td>'
>>> BeautifulSoup(text1).td.font.nextSibling
u'  16043646'
>>> BeautifulSoup(text2).td.font.nextSibling
>>>
相关问题