我正在尝试使用lxml从字符串中读取html然后尝试查找所有img标记,更新图像src的属性并在找到的每个图像周围添加超链接
所以这个,
<img src="old-value" />
将是这个
<a href=""><img src="new-value" /></a>
我面临的问题是两个,首先是使用etree.HTML加载html字符串,由于某种原因,它将html标签和body标签添加到html本身。有没有办法加载它而不会自动导致这种情况发生?
另一个问题无法解决,我如何在图片标签周围添加超链接元素,我尝试了下面但它会在img标签内添加超链接元素
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)
任何人都可以提出建议吗?
更新
我刚试过@Alko提供的方法,并且运行良好,但是我使用的内容类型存在问题。
img标签位于p标签内,例如下面的示例
<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>
当我运行给定的解决方案时发生了什么,在段落结束后添加了一个标签。
答案 0 :(得分:3)
您可以在插入之前使用addprevious
:
imgs = tree.xpath('.//img')
thm = "new-value"
for img in imgs:
img.set('src', thm)
a = etree.Element('a', href="#")
img.addprevious(a)
a.insert(0, img)
这将导致
>>> etree.tostring(tree)
'<html><body><a href="#"><img src="new-value"/></a></body></html>'
此外,lxml.html.fragment_fromstring
可能很有用,但您必须提供更多样化的示例,因为在单独的图像元素的情况下,您的xpath将无法找到它。
参见以下演示:
>>> import lxml.html
>>> img = lxml.html.fragment_fromstring('<img src="old-value" />')
>>> thm = "new-value"
>>> img.set('src', thm)
>>> a = etree.Element('a', href="#")
>>> a.insert(0, img)
>>> lxml.html.etree.tostring(a)
'<a href="#"><img src="new-value"/></a>'
<强>更新强>
对于img
标记有尾标的情况,您可以将其重新分配给已创建的a
标记:
>>> s = '<html><body><p><img src="old_value"/>some text</p></body></html>'
>>> tree = etree.HTML(s)
>>> imgs = tree.xpath('.//img')
>>> thm = "new-value"
>>> for img in imgs:
... img.set('src', thm)
... a = etree.Element('a', href="#")
... img.addprevious(a)
... a.insert(0, img)
... a.tail = img.tail
... img.tail = ''
...
>>> etree.tostring(tree)
'<html><body><p><a href="#"><img src="new-value"/></a>some text</p></body></html>'
答案 1 :(得分:0)
holder = etree.Element('div', {'id': 'links'})
for img in imgs:
a_tag = etree.SubElement( holder, {'href':'#'} )
img_tag = etree.SubElement( a_tag, {'src': 'new_value'} )
etree.toString(holder)