I made this by downloading external sources (images) and replacing their src
attribute.
Let's assume I want to save all images from <img>
tags to the ../images
path relative to the current page.
~/site
~/site/pages/
~/site/pages/page1.html
~/site/pages/page2.html
~/site/images/
~/site/images/img_for_page1.png
~/site/images/img_for_page2.png
I download the images with requests module.
# save_full_page.py
from selenium import webdriver
import requests
... # open page you want to save
with open("replace_img_srcs.js", 'r') as file:
replace_img_srcs_js = file.read()
save_dir = "/home/user/site"
save_to_file = "/home/user/site/pages/page1.html"
img_tags = driver.find_elements(By.TAG_NAME, "img")
for img_tag in img_tags:
img_src = img_tag.get_attribute("src")
r = requests.get(img_src, allow_redirects=True)
img_filename = img_src.rsplit('/', 1)[1]
open(save_dir + "/images/" + img_filename, 'wb').write(r.content)
driver.execute_script(replace_img_srcs_js) # see below
with open(save_to_file, 'w') as f:
f.write(driver.page_source)
This code edits the src attribute. I placed it to separate file to be able to see syntax highlighting. You can place the contents of it directly to the driver.execute_script(...)
if you wish.
// replace_img_srcs.js
Array.prototype.slice.call(document.getElementsByTagName('img')).forEach(
function(item) {
var img_src = item.src;
var img_filename = img_src.replace(/^.*[\\\/]/, '');
var img_filename_urlencoded = encodeURIComponent(img_filename) // because images may be named with encoded symbols
item.src = item.src.replace(img_src, "../images/" + img_filename_urlencoded);
}
)
Now we have page saved for autonomous use.