【问题标题】:How can I emulate ":contains" using BeautifulSoup?如何使用 BeautifulSoup 模拟“:contains”?
【发布时间】:2012-06-06 17:11:16
【问题描述】:

我正在做一个项目,我需要一点点刮擦。该项目位于 Google App Engine 上,我们目前使用的是 Python 2.5。理想情况下,我们会使用 PyQuery,但由于在 App Engine 和 Python 2.5 上运行,这不是一个选项。

我在finding an HTML tag with certain text 上看到过类似的问题,但它们并没有完全达到目标。

我有一些看起来像这样的 HTML:

<div class="post">
    <div class="description">
        This post is about <a href="http://www.wikipedia.org">Wikipedia.org</a>
    </div>
</div>
<!-- More posts of similar format -->

在 PyQuery 中,我可以做这样的事情(据我所知):

s = pq(html)
s(".post:contains('This post is about Wikipedia.org')")
# returns all posts containing that text

天真地,我以为我可以在 BeautifulSoup 中做这样的事情:

soup = BeautifulSoup(html)
soup.findAll(True, "post", text=("This post is about Google.com"))
# []

但是,这没有产生任何结果。我将查询更改为使用正则表达式,并且走得更远,但仍然没有运气:

soup.findAll(True, "post", text=re.compile(".*This post is about.*Google.com.*"))
# []

如果我省略Google.com,它会起作用,但是我需要手动进行所有过滤。 是否可以使用 BeautifulSoup 模拟 :contains

或者,是否有一些类似 PyQuery 的库可以在 App Engine(在 Python 2.5 上)上运行?

【问题讨论】:

  • 为什么不迁移到lxml is available 的2.7?
  • 我们绝对想要,只是还没有做到。旧代码库,没有足够的时间等。这是一个公平的批评。
  • 好吧,migration 似乎并不太复杂,而且由于您的应用程序是版本化的,您可以尝试一下,如果它不起作用,则返回。
  • 感谢您的建议。我们确实尝试过。我们过去的一位开发人员太聪明了,这使事情变得更加复杂:(

标签: python google-app-engine beautifulsoup


【解决方案1】:

来自 BeautifulSoup 文档(重点是我的):

"text 是一个参数,可让您搜索 NavigableString 对象 而不是标签”

也就是说,你的代码:

soup.findAll(True, "post", text=re.compile(".*This post is about.*Google.com.*"))

不等于:

regex = re.compile('.*This post is about.*Google.com.*')
[post for post in soup.findAll(True, 'post') if regex.match(post.text)]

您必须删除 Google.com 的原因是,BeautifulSoup 树中有一个 NavigableString 对象用于"This post is about",另一个用于"Google.com",但它们位于不同的元素下。

顺便说一句,post.text 存在但没有记录,所以我也不会依赖它,我偶然编写了该代码!使用其他方法将post 下的所有文本混合在一起。

【讨论】:

  • 我确实读过那句话,但无法理解其中的区别。这绝对是我需要的。谢谢:)
  • @NT3RP “无法理解其中的区别”:对我来说也是如此,BeautifulSoup 文档在 IMO 中真是一团糟。 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 2011-08-07
  • 2010-09-16
  • 1970-01-01
  • 2015-12-24
相关资源
最近更新 更多