Changing all images of a site in selenium

Viewed 31

Hi I'm tryna access a site and get all the images and replace it with my own. So in this case change the images on google.com . I've come this far but the google image is not changing but i can see it changed when I inspect the element. What do I have to do to see the change reflected?

from selenium.webdriver.chrome.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By
    
s = Service(chrome)      

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])

driver = webdriver.Chrome(service=s, options=options)

driver.get("https:/www.google.com/")
 


element = driver.find_element(By.TAG_NAME, "img")
driver.execute_script("arguments[0].setAttribute('src', 'C:/img/change.png');", element);
1 Answers

Replacing images on Google is slightly more difficult. Firstly, you are referring to an image on your local machine, and I'm not sure if that's even allowed. You would have better luck using an image that is on the internet. You would also have to change more than just the img tag to get the image to change. In the case of the main Google logo, you would also have to change the srcset attribute. So something like this would work:

driver.execute_script("arguments[0].setAttribute('src', 'https://bobraley.files.wordpress.com/2016/08/image1.jpeg');", element)
driver.execute_script("arguments[0].setAttribute('srcset', 'https://bobraley.files.wordpress.com/2016/08/image1.jpeg 1x, https://bobraley.files.wordpress.com/2016/08/image1.jpeg 2x');", element)

Unless you specifically want to change the imgaes on Google, you would be better off testing on a simpler site.

Related