BeautifulSoup,简单的正则表达式问题

3

我刚用正则表达式遇到了一些问题,不知道为什么它不能工作。

以下是BeautifulSoup文档中的内容:

soup.find_all(class_=re.compile("itl"))
# [<p class="title"><b>The Dormouse's story</b></p>]

以下是我的HTML代码:

<a href="exam.com" title="Keeper: Jay" class="pos_text">Aouate</a></span><span class="pos_text pos3_l_4">

我正在尝试匹配标签(最后一个位置)。

>>> if soup.find(class_=re.compile("pos_text pos3_l_\d{1}")):
        print "Yes"

# prints nothing - indicating there is no such pattern in the html

所以,我只是在重复BS4文档,但我的正则表达式不起作用。如果我将\d{1} 替换为4(与HTML中最初的相同),它就可以成功了。

3个回答

2

在你的正则表达式中试用"\\d"。它可能会将"\d"解释为试图转义'd'。

或者,使用原始字符串应该可以解决问题。只需在正则表达式前面加上'r',像这样:

re.compile(r"pos_text pos3_l_\d{1}")

为什么d需要转义? - PuercoPop
d 不需要转义。\\ 需要转义。 - Joe Frambach
嗯,我已经使用\d很多次了,但从未转义过反斜杠。不过我现在尝试了一下,但它什么也没做。 - nutship

2

我不能完全确定,但这对我有效:

soup.find(attrs={'class':re.compile('pos_text pos3_l_\d{1}')})

从文档中可以看到:Beautiful Soup 的所有版本都提供了一个 class_ 快捷方式。任何 find() 类型方法的第二个参数都称为 attrs,并且将字符串传递给 attrs 将搜索该字符串作为 CSS 类: - PuercoPop
哦,很棒。我从来没有注意到那个。 - Joe Frambach

1
你正在匹配不是一个类,而是一个特定顺序的特定类组合。
来自文档
You can also search for the exact string value of the class attribute:

css_soup.find_all("p", class_="body strikeout")
# [<p class="body strikeout"></p>] But searching for variants of the string value won’t work:

css_soup.find_all("p", class_="strikeout body")
# []

所以你应该先匹配post_text,然后在结果中尝试使用匹配搜索的正则表达式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接