Beautiful Soup - 获取第一个指定标签后的字符串

0 投票
2 回答
2098 浏览
提问于 2025-04-17 09:40

我想要获取紧跟在开头的 <td> 标签后面的字符串。以下代码可以正常工作:

webpage = urlopen(i).read()
soup = BeautifulSoup(webpage)
for elem in soup('td', text=re.compile(".\.doc")):
    print elem.parent

当 HTML 看起来像这样时:

<td>plan_49913.doc</td>

但当 HTML 看起来像这样时,它就不行了:

<td>plan_49913.doc<br /> <font color="#990000">文档已被替代: &#160;</font><a href="/plans/Jan_2012.html">2012年1月</a></td>

我尝试过使用 attrs,但就是无法让它工作。基本上,我只想在这两种 HTML 情况下都能获取到 'plan_49913.doc'。

任何建议都将非常感激。

提前谢谢你。

~chrisK

2 个回答

1

这个对我有效:

>>> html = '<td>plan_49913.doc<br /> <font color="#990000">Document superseded by: &#160;</font><a href="/plans/Jan_2012.html">January 2012</a></td>'
>>> soup = BeautifulSoup(html)
>>> soup.find(text=re.compile('.\.doc'))
u'plan_49913.doc

我是不是漏掉了什么?

另外,根据文档的说明:

如果你使用文本,那么你给的名字和关键字参数的值都会被忽略。

所以你不需要传递 'td',因为它已经被忽略了,也就是说,任何在其他标签下匹配的文本都会被返回。

0

只需要使用 next 这个属性,它包含了下一个节点,而这个节点是一个文本节点。

>>> html = '<td>plan_49913.doc<br /> <font color="#990000">Document superseded by: &#160;</font><a href="/plans/Jan_2012.html">January 2012</a></td>'
>>> bs = BeautifulSoup(html)
>>> texts = [ node.next for node in bs.findAll('td') if node.next.endswith('.doc') ]
>>> texts
[u'plan_49913.doc']

如果你喜欢的话,可以把 if 这个条件改成使用正则表达式。

撰写回答