python - 如何使用 BeautifulSoup 模拟 ":contains"?

标签 python google-app-engine beautifulsoup

我正在做一个项目,需要进行一些整理。该项目在 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 上)上运行?

最佳答案

来自 BeautifulSoup 文档(强调我的):

"text is an argument that lets you search for NavigableString objects instead of Tags"

也就是说,你的代码:

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 下的所有文本拼凑在一起。

关于python - 如何使用 BeautifulSoup 模拟 ":contains"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10918898/

相关文章:

python - 超时无法使用 urllib2、socks5 代理和 socksipy

python - pandas pd.ExcelWriter 和 xlrd 将 python 数据帧输出为 excel 文件

python - jinja2 的 autoescape 扩展和 markupsafe 库的区别

java - 用于在 Java7 上运行的 GAE 的 BigTable SDK

python - BeautifulSoup' 没有属性 'HTML_ENTITIES

Python:如何从 gmail API 获取电子邮件的主题

python - xlsx writer set_row 有时不起作用

java - 通过 http 监视文本文件的更改

python - Scrapy 或 BeautifulSoup 从各种网站上抓取链接和文本

python - Pandas 追加到系列中