Note that there are some explanatory texts on larger screens.

plurals
  1. POReplacing an element with HTMLParser in python and using pscyopg2
    primarykey
    data
    text
    <p>In my database I have values like this:</p> <pre><code>&lt;p class="description"&gt;Text here &lt;a href=#&gt;Text here&lt;/a&gt; &lt;/p&gt; </code></pre> <p>And I need that whole <code>&lt;p&gt;</code> object to replace the same <code>&lt;p class="description&gt;</code> in a template file.</p> <pre><code>import sys from HTMLParser import HTMLParser from xml.etree import cElementTree as etree import psycopg2 import psycopg2.extras class LinksParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.tb = etree.TreeBuilder() def handle_starttag(self, tag, attributes): self.tb.start(tag, dict(attributes)) def handle_endtag(self, tag): self.tb.end(tag) def handle_data(self, data): self.tb.data(data) def close(self): HTMLParser.close(self) return self.tb.close() conn = psycopg2.connect(dbname="**", user="**", password="**", host="/tmp/", port="**") cur.execute("SELECT * FROM landingpagedata;") row = cur.fetchone() template = 'template.html' parser = LinksParser() parser.feed(open(template).read()) root = parser.close() #p_class_description p = root.find(".//p[@class='description']") p.text = str(row['p_class_description']) f = open(row['new_html_page'], 'w') root.write(f) parser = LinksParser() </code></pre> <p>What I end up with in the file is this:</p> <pre><code>&lt;p class="suggested_readings"&gt;&amp;lt;p class="suggested_readings"&amp;gt;Text here &amp;lt;a href=#;"&amp;gt;Text here &amp;lt;/a&amp;gt;.&amp;lt;/p&amp;gt; &lt;a href=#&gt;Text from template&lt;/a&gt; and more from template&lt;/p&gt; </code></pre> <p>I can't seem to replace the whole element with this element. Or, should I be trying to store an actual element in my database? So helpless here.</p> <p>Thanks!!!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload