am trying to use lxml to read html from a string and then try to find all img tags, update the image src's attribute and add hyper link around each image found
so this,
<img src="old-value" />
will be this
<a href=""><img src="new-value" /></a>
the problem am facing is two, first am using etree.HTML to load the html string, which for some reason is adding html tag and body tag to the html itself. Is there a way to load it without automatically causing this to happen?
Another problem am not able to solve, how do i add the hyper link element around the image tag, I tried the below but it would add the hyper link element inside the img tag
tree = etree.HTML(self.content)
imgs = tree.xpath('.//img')
thm = "new-value"
for img in imgs:
img.set('src', thm)
a = etree.Element('a', href="#")
img.insert(0, a)
Any one can advise please?
update:
I just tried the approach provided by @Alko and its working well, but it has a problem with the type of content am using.
The img tag is located inside p tags such as example below
<html><body><p><img src="/public_media/cache/66/ed/66edd1c01e3027ba18bef9244ca8e8b4.jpg?id=31"/>jshjksh skjhs jksh skjhsj ksh jkshs kjhs kjsh sjkhs khs ksh skh skh skjh skjh skjh ksjh ksh skhs kjsh skjh skhs khs kjsh skjh skjhs kshk sjh skjhs kjsh skjh skjh ksj ksjh jsk hskjh s</p><p>jshjksh skjhs jksh skjhsj ksh jkshs kjhs kjsh sjkhs khs ksh skh skh skjh
skjh skjh ksjh ksh skhs kjsh skjh skhs khs kjsh skjh skjhs kshk sjh
skjhs kjsh skjh skjh ksj ksjh jsk hskjh s</p></body></html>
whats happening when i run the solution given, the closing a tag is being added after the ending of the paragraph.