【问题标题】:Python Find & Replace Beautiful SoupPython 查找和替换 Beautiful Soup
【发布时间】:2011-07-13 05:03:01
【问题描述】:

我正在使用 Beautiful Soup 将出现的模式替换为 HTML 文件中的 href 链接

我遇到了如下所述的问题

modified_contents = re.sub("([^http://*/s]APP[a-z]{2}[0-9]{2})", "<a href=\"http://stack.com=\\1\">\\1</a>", str(soup))

示例输入 1:

Input File contains APPdd34

Output File contains <a href="http://stack.com=APPdd34"> APPdd34</a>

示例输入 2:

Input File contains <a href="http://stack.com=APPdd34"> APPdd34</a>

Output File contains <a href="http://stack.com=<a href="http://stack.com=APPdd34"> APPdd34</a>"> <a href="http://stack.com=APPdd34"> APPdd34</a></a>

所需的输出文件 2 与示例输入文件 2 相同。

我该如何解决这个问题?

【问题讨论】:

  • 你需要的不是[^...],而是一个negative lookbehind assertion(最后是一个negative lookahead assertion)。在 Python 手册中阅读它。
  • 您可能会发现pythex 很有用,它可以让您实时测试您的python 正则表达式。

标签: python html find beautifulsoup


【解决方案1】:

这可能无法完全回答您的问题,因为我不知道整个输入文件可能是什么样子,但我希望这是您可以采取的方向。

from BeautifulSoup import BeautifulSoup, Tag
text = """APPdd34"""
soup = BeautifulSoup(text)
var1 = soup.text
text = """&lt;a href="http://stack.com=APPdd34"&gt; APPdd34&lt;/a&gt;"""
soup = BeautifulSoup(text)
var2 = soup.find('a').text

soup = BeautifulSoup("&lt;p>Some new html&lt;/p&gt;")
tag1 = Tag(soup, "a",{'href':'http://stack.com='+var1,})
tag1.insert(0,var1) # Insert text
tag2 = Tag(soup, "a",{'href':'http://stack.com='+var2,})
tag2.insert(0,var2)
soup.insert(0,tag1)
soup.insert(3,tag2)
print soup.prettify()

所以基本上,只需使用 BeautifulSoup 提取文本,然后您就可以从那里构建标签。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 2018-07-27
    相关资源
    最近更新 更多