【问题标题】:BeautifulSoup passing regex as argumentBeautifulSoup 将正则表达式作为参数传递
【发布时间】:2013-03-28 21:18:12
【问题描述】:

我有这个 html:

title="Keeper: Michal Buchalik" class="pos_text">Buchalik</a></span>                
                                            <span class="pos_text pos3_l_5">

我尝试匹配Buchalik

我想出了这个代码:

for gk in soup.find_all(re.compile("pos_text pos3_l_\d{1,2}")):
    print gk.previous_element.previous_element,

它不匹配任何东西,正则表达式一定有问题,因为当我输入某个数字代替\d{1,2} 时,它工作得很好。

【问题讨论】:

  • 我在我的正则表达式中发现了一个明显的错误,这部分代码丢失了class_=,尽管它仍然没有给我预期的输出。

标签: python regex python-2.7 beautifulsoup


【解决方案1】:

由于是python,你需要使用r来表示“原始文本”或转义'\'字符:

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

OR

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

看看有没有帮助。

干杯。

【讨论】:

  • 感谢回复,不过上面不需要转义。请注意,在原始 HTML 页面中,没有反斜杠字符。
  • 是的,但是您的正则表达式使用 \d (数字)构造。因此,需要转义的不是文本,而是正则表达式本身。试试看?
  • 看来问题不在于正则表达式 - 因为 re.compile("pos_text pos3_l_\d{1,2}").split() 似乎按预期行事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
  • 2016-02-24
  • 1970-01-01
相关资源
最近更新 更多