How to replace links using lxml and iterlinks
Instead of just assigning a new (string) value to the variable name link
, you have to alter the element itself, in this case by setting its src
attribute:
new_src = link.replace('foo', 'bar') # or element.get('src').replace('foo', 'bar')
element.set('src', new_src)
Note that - if you know which "links" you are interested in, for example, only img
elements - you can also get the elements by using .findall()
(or xpath or css selectors) instead of using .iterlinks()
.