【问题标题】:BeautifulSoup, simple regex issueBeautifulSoup,简单的正则表达式问题
【发布时间】:2013-04-01 07:28:48
【问题描述】:

我只是遇到了正则表达式的障碍,不知道为什么这不起作用。

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 文档,但我的正则表达式不起作用。如果我用4(最初在html中)替换\d{1},它就成功了。

【问题讨论】:

    标签: python regex python-2.7 beautifulsoup


    【解决方案1】:

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

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

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

    【讨论】:

    • 为什么需要转义?
    • d 不需要转义。 `\` 需要转义。
    • 嗯,我已经多次使用\d 并且从未真正逃脱过反斜杠。无论如何我现在都试过了,但它什么也没做。
    【解决方案2】:

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

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

    【讨论】:

    • 来自文档:所有版本的 Beautiful Soup 中都有一个 class_ 的快捷方式。任何 find() 类型方法的第二个参数称为 attrs,传入一个字符串作为 attrs 将搜索该字符串作为 CSS 类:
    • 哦,太好了。我从来没有注意到这一点。
    【解决方案3】:

    您匹配的不是一个类,而是一个特定顺序的特定类组合。

    来自documentation

    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,然后在结果中尝试与该搜索匹配中的正则表达式匹配

    【讨论】:

      猜你喜欢
      • 2011-05-13
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 2013-11-02
      相关资源
      最近更新 更多