在python中使用HTMLParser替换元素并使用pscyopg2

在python中使用HTMLParser替换元素并使用pscyopg2,python,html-parsing,psycopg2,Python,Html Parsing,Psycopg2,在我的数据库中,我有如下值: <p class="description">Text here <a href=#>Text here</a> </p> for row in rows: parser = etree.HTMLParser() root = etree.parse(template) p_class_aboutmaterials = root.find(".//p[@class='about_material

在我的数据库中,我有如下值:

<p class="description">Text here
    <a href=#>Text here</a>
</p>
for row in rows:
  parser = etree.HTMLParser()
  root = etree.parse(template)

  p_class_aboutmaterials = root.find(".//p[@class='about_materials']")
  div_class_aboutmaterials = p_class_aboutmaterials.getparent()
  div_class_aboutmaterials.remove(p_class_aboutmaterials)
  div_class_aboutmaterials.append(etree.XML(row['p_class_aboutmaterials']))
我在文件中得到的结果是:

<p class="suggested_readings">&lt;p class="suggested_readings"&gt;Text here &lt;a href=#;"&gt;Text here &lt;/a&gt;.&lt;/p&gt;
 <a href=#>Text from template</a> and more from template</p>

p class=“建议的阅读”文本此处a href=#;“此处为文本/a./p 还有来自模板的更多信息

我似乎不能用这个元素替换整个元素。或者,我应该尝试在我的数据库中存储一个实际的元素吗?这里太无助了


谢谢!!!

我最终通过使用解决了这个问题。因此,现在top使用以下方法:

import sys
from lxml import etree
from StringIO import StringIO
import psycopg2
import psycopg2.extras
实现如下所示:

<p class="description">Text here
    <a href=#>Text here</a>
</p>
for row in rows:
  parser = etree.HTMLParser()
  root = etree.parse(template)

  p_class_aboutmaterials = root.find(".//p[@class='about_materials']")
  div_class_aboutmaterials = p_class_aboutmaterials.getparent()
  div_class_aboutmaterials.remove(p_class_aboutmaterials)
  div_class_aboutmaterials.append(etree.XML(row['p_class_aboutmaterials']))
我注定要得到转义的html,因为我正在将它转换为字符串。
Getparent()和remove()允许我替换模板中已经存在的内容。

在您的数据库中是否有
p
且列名为
p\u class\u description
?是。很抱歉,不清楚。在
解析器中。提要()
打开模板,然后在数据库的
中查找名为
description
的类。