python - 正则表达式替换 html 文档中的文本节点

标签 python html regex replace lxml

我有一个代表 html 文档的字符串。我试图用一些替换 html 替换该文档中的文本,当然排除标记和属性值。我认为这很简单,但是当您想用标记替换文本时,这非常乏味。例如,替换 somekeyword<a href = "link">somekeyword</a> .

from lxml.html import fragments_fromstring, fromstring, tostring
from re import compile
def markup_aware_sub(pattern, repl, text):
    exp = compile(pattern)
    root = fromstring(text)

    els = [el for el in root.getiterator() if el.text]
    els = [el for el in els if el.text.strip()]
    for el in els:
        text = exp.sub(repl, el.text)
        if text == el.text:
            continue
        parent = el.getparent()
        new_el = fromstring(text)
        new_el.tag = el.tag
        for k, v in el.attrib.items():
            new_el.attrib[k] = v
        parent.replace(el, new_el)
    return tostring(root)

markup_aware_sub('keyword', '<a>blah</a>', '<div><p>Text with keyword here</p></div>')

它有效,但前提是关键字正好是两个“嵌套”。必须有比上面更好的方法,但在谷歌搜索几个小时后我找不到任何东西。

最佳答案

这可能是您正在寻找的解决方案:

from HTMLParser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self,link, keyword):
    HTMLParser.__init__(self)
    self.__html = []
    self.link = link
    self.keyword = keyword

    def handle_data(self, data):
    text = data.strip()
    self.__html.append(text.replace(self.keyword,'<a href="'+self.link+'>'+self.keyword+'</a>'))

    def handle_starttag(self, tag, attrs):
    self.__html.append("<"+tag+">")

    def handle_endtag(self, tag):
    self.__html.append("</"+tag+">")

    def new_html(self):
    return ''.join(self.__html).strip()


parser = MyParser("blah","keyword")
parser.feed("<div><p>Text with keyword here</p></div>")
parser.close()
print parser.new_html()

这将为您提供以下输出

<div><p>Text with <a href="blah>keyword</a> here</p></div>

您的 lxml 方法的问题似乎仅在关键字只有一个嵌套时才会出现。它似乎适用于多个嵌套。所以我添加了一个if条件来捕获这个异常。

from lxml.html import fragments_fromstring, fromstring, tostring
from re import compile
def markup_aware_sub(pattern, repl, text):
    exp = compile(pattern)
    root = fromstring(text)
    els = [el for el in root.getiterator() if el.text]
    els = [el for el in els if el.text.strip()]

    if len(els) == 1:
      el = els[0]
      text = exp.sub(repl, el.text)
      parent = el.getparent()
      new_el = fromstring(text)
      new_el.tag = el.tag
      for k, v in el.attrib.items():
          new_el.attrib[k] = v
      return tostring(new_el)

    for el in els:
      text = exp.sub(repl, el.text)
      if text == el.text:
        continue
      parent = el.getparent()
      new_el = fromstring(text)
      new_el.tag = el.tag
      for k, v in el.attrib.items():
          new_el.attrib[k] = v
      parent.replace(el, new_el)
    return tostring(root)

print markup_aware_sub('keyword', '<a>blah</a>', '<p>Text with keyword here</p>')

不太优雅,但似乎可行。请检查一下。

关于python - 正则表达式替换 html 文档中的文本节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7915812/

相关文章:

html - 将 `position: fixed` 应用到 `body` 使其失去滚动条

regex - 用于在 HTTP url 中检索文件扩展名的正则表达式

python - "implicit uses of special methods always rely on the class-level binding of the special method"

Python 将变量输出拆分为多个变量

javascript - 是否可以在选择时绑定(bind)选择选项而不是在更改时绑定(bind)

javascript - 如何根据 JSON 属性名称替换字符串值

c# - 形成一个正则表达式来解析数值表达式

python - 向量化 Pandas 列

python - 在这段代码中,Python 的 timeit(...) 方法实际计时的代码是什么?

javascript - 仅更改 <object> 标签的属性,其中包含使用 jQuery 的 SVG 元素