【问题标题】:Beautiful Soup / regex matching over multiple lines美丽的汤/正则表达式匹配多行
【发布时间】:2013-06-29 02:49:15
【问题描述】:

我基本上有一个用 Python 编写的 RSS 索引应用程序,它将 RSS 内容作为简介存储在数据库中。应用最初处理文章内容时,会注释掉所有不符合特定条件的链接,例如:

<a href="http://google.com">Google</a>

成为:

<!--<a href="http://google.com">Google</a>--> Google

现在我需要处理所有这些旧文章并修改链接。所以使用 BeautifulSoup 4 我可以很容易地找到 cmets 使用:

links = soup.findAll(text=lambda text:isinstance(text, Comment))
for link in links:
    text = re.sub('<[^>]*>', '', link.string)
    # any html in the link tag was escaped by BS4, so need to convert back
    text = text.replace('&amp;lt;','<')
    text = text.replace('&amp;gt;','>')
    find = link.string + " " + text

上面“find”的输出是:

<!--<a href="http://google.com">Google</a>--> Google

这样可以更轻松地对内容执行.replace()

现在我遇到的问题(我相信这很简单)是多行查找/替换。当 Beautiful Soup 最初注释掉链接时,一些链接被转换为:

<!--<a href="http://google.com">Google
</a>--> Google

<!--<a href="http://google.com">Google</a>--> 
Google

很明显,replace(old,new) 不起作用,因为replace() 不涵盖多行。

有人可以帮助我使用正则表达式多行查找/替换吗?它应该区分大小写。

【问题讨论】:

  • 如果你不想打扰(并且可以在不改变页面内容的情况下做到这一点),最明显的处理方法是将所有 HTML 放在一行中,这样替换变得很容易。
  • 看看herehere

标签: python regex beautifulsoup


【解决方案1】:

试试这个:

 re.sub(r'pattern', '', link, flags=re.MULTILINE)

正则表达式匹配默认区分大小写。

如果由于某种原因 RSS 文件变得不规则,您的脚本将会失败。在这种情况下,您应该考虑使用适当的解析器,例如lxml

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-21
    • 2012-05-05
    • 1970-01-01
    • 2013-04-09
    • 2014-09-05
    • 2017-12-14
    • 1970-01-01
    相关资源
    最近更新 更多