Reputation: 9533
I found solution in Python to Search and Replace all img
tag in HTML String:
I have a HTMl String:
"<h1>H1 Tag</h1>\n<p>foo <img alt=\"alt\" src=\"image_2.jpg\
bar</p>\n<p>11</p>\n<h2>H2
Tag</h2>\n<p>ads\nad\nad\nad</p>\n<h3>Imsd</h3>\n<p><img alt=\"alt\"
src=\"image_3.jpg\"
I want to Search and Replace all img tag in HTML String by adding base URL https://domman.com
. So this results I want:
"<h1>H1 Tag</h1>\n<p>foo <img alt=\"alt\" src=\"https://domman.com/image_2.jpg\
bar</p>\n<p>11</p>\n<h2>H2
Tag</h2>\n<p>ads\nad\nad\nad</p>\n<h3>Imsd</h3>\n<p><img alt=\"alt\"
src=\"https://domman.com/image_3.jpg\"
Upvotes: 0
Views: 2233
Reputation: 213
You can use BeautifulSoup To replace all src of img tag.
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_str)
for img in soup.findAll('img'):
img['src'] = 'https://domman.com/'+img['src']
html_str = str(soup)
Upvotes: 7
Reputation: 420
import lxml.html
html = lxml.html.fromstring("""<h1>H1 Tag</h1>\n<p>foo <img alt="alt"
src="image_2.jpg">
bar</p><p>11</p>\n<h2>H2 Tag</h2>\n<p>
ads\nad\nad\nad</p>\n<h3>Imsd</h3>\n<p><img alt="alt" src="image_3.jpg">""")
imgs = html.xpath("//img")
for img in imgs:
img.attrib["src"] = "https://domman.com/" + img.attrib["src"]
with open("page.html", "wb") as f:
f.write(lxml.html.tostring(html))
this is it
Upvotes: 1