Skip to content
Advertisement

change image src using selenium webdriver

I have a project in where I want to upload image to image tag in web page using upload box , I can do that by selenium web driver by opening the upload box then writing the image path then pressing open .I tried to ignore the upload box by changing the image attribute “src” but I could not do that. I tried the following code but it does not make any changes.

                        String script = "document.getElementById('img1').src='" + "C:\Uploading files\276090223\276090223.jpg" + "';";

                        ((IJavaScriptExecutor)driver).ExecuteScript(script);

how can I change the image src attribute which takes its value from javascript method?

Advertisement

Answer

Assuming the 'img1' ID is unique, I’d try

IWebElement Element = driver.FindElement(By.Id("img1"));
((IJavaScriptExecutor) driver).ExecuteScript("arguments[0].setAttribute('src', 'C:\Uploading files\276090223\276090223.jpg');", Element);
Advertisement