...
<img alt='fdsfsd' src='text1 text2'/>
adasd
<img alt='sadsdd' src='text3 text4'/>
adasdas
...
...
<img alt='fdsfsd' src='CONST_text1_text2'/>
adasd
<img alt='sadsdd' src='CONST_text3_text4'/>
adasdas
...
import re
from lxml import etree
doc = \
"""
<body>
<img alt='fdsfsd' src='CONST text1 text2'/>
adasd
<img alt='sadsdd' src='CONST text3 text4'/>
adasdas
</body>
"""
tree = etree.fromstring(doc, parser=etree.HTMLParser())
for img in tree.xpath('//img[@src]'):
img.attrib['src'] = re.sub(r'\s+', '_', img.attrib['src'])