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">

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

>>> 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 中)替换它就成功了。

4

3 回答 3

2

在您的正则表达式中尝试“\\d”。它可能将“\d”解释为试图逃避“d”。

或者,原始字符串应该可以工作。只需在正则表达式前面放一个“r”,如下所示:

re.compile(r"pos_text pos3_l_\d{1}")
于 2013-04-09T18:19:27.943 回答
2

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

soup.find(attrs={'class':re.compile('pos_text pos3_l_\d{1}')})
于 2013-04-09T18:19:54.330 回答
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 进行第一次匹配,然后在结果中尝试与该搜索匹配中的正则表达式匹配

于 2013-04-09T18:24:40.563 回答