如何使用 Beautiful Soup 查找带有特定文本的标签? [英] How to find tag with particular text with Beautiful Soup?

查看:74
本文介绍了如何使用 Beautiful Soup 查找带有特定文本的标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在以下 HTML 中查找我要查找的文本(用 标记的换行符)?

How to find text I am looking for in the following HTML (line breaks marked with )?

...
<tr>
  <td class="pos">

      "Some text:"

      <br>

      <strong>some value</strong>

  </td>
</tr>
<tr>
  <td class="pos">

      "Fixed text:"

      <br>

      <strong>text I am looking for</strong>

  </td>
</tr>
<tr>
  <td class="pos">

      "Some other text:"

      <br>

      <strong>some other value</strong>

  </td>
</tr>
...

下面的代码返回第一个找到的值,所以我需要通过 "Fixed text:" 以某种方式过滤.

The code below returns first found value, so I need to filter by "Fixed text:" somehow.

result = soup.find('td', {'class' :'pos'}).find('strong').text

更新:如果我使用以下代码:

UPDATE: If I use the following code:

title = soup.find('td', text = re.compile(ur'Fixed text:(.*)', re.DOTALL), attrs = {'class': 'pos'})
self.response.out.write(str(title.string).decode('utf8'))

然后它只返回 Fixed text:,而不是 <strong> 在同一元素中突出显示的文本.

then it returns just Fixed text:, not the <strong>-highlighted text in that same element.

推荐答案

你可以给 findAll 的 text 参数传递一个正则表达式,像这样:

You can pass a regular expression to the text parameter of findAll, like so:

import BeautifulSoup
import re

columns = soup.findAll('td', text = re.compile('your regex here'), attrs = {'class' : 'pos'})

这篇关于如何使用 Beautiful Soup 查找带有特定文本的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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