【问题标题】:Searching for strings with BeuatifulSoup使用 BeautifulSoup 搜索字符串
【发布时间】:2016-05-03 21:34:48
【问题描述】:

我希望下面的代码

from bs4 import BeautifulSoup
import re
sopa = BeautifulSoup('<ol><li>this is a string</li></ol>')
sopa.find_all(string=re.compile("a"))

会返回[u'this is a string'],但它会返回[]。为什么?

BeautifulSoup 4 文档给出了这个例子:

soup.find_all(string=re.compile("Dormouse"))

当作用于爱丽丝梦游仙境节选的汤时,应该返回

[u"The Dormouse's story", u"The Dormouse's story"]

文档还说 bs4 使用 re.match()(匹配字符串的开头),但其他地方(以及官方文档中的这个示例)指示 re.search(),并将正则表达式 "a" 更改为 @ 987654329@无论如何对结果都没有影响。

【问题讨论】:

  • 已解决。版本 text

标签: regex python-2.7 beautifulsoup


【解决方案1】:

如果你打印最后一行,它也可以工作,我试过了,它工作

print(sopa.find_all(string=re.compile("a")))

也可以通过

获取文本
print(sopa.getText())

第三种方法

print(sopa.get_text())

【讨论】:

    猜你喜欢
    • 2012-02-14
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2013-01-26
    • 2014-03-20
    相关资源
    最近更新 更多