简体   繁体   中英

Selenium webdriver : How to get embedded image data using JavaScripts?

I have to get the src from below mentioned html, please let me know how can I get the embedded image data? Is this possible using JS? If there is any way to show to the hide elements? I am using Selenium web driver with Java.

<div id="sc859" class="atv4 alc sc-view c-image sc-hidden" style="left: 0px; right: 0px; top: 0px; bottom: 0px">
    <img style="height: 100%; width: 100%;" src="data:image/gif;base64,R0lGODlhAQABAJAAAP///wAAACH5BAUQAAAALAAAAAABAAEAAAICBAEAOw==" class="alc-img"/>
</div>

My code:

JavascriptExecutor jse = (JavascriptExecutor)driver; 
WebElement element = driver.findElement(By.cssSelector("#sc859")); 
String imgeJs = (String) jse.executeScript("document.getElementsById('sc859')[0].getAttribute('src');", element);
System.out.println(imgeJs);

Try this:

WebElement div = driver.findElement(By.id("sc859"));
String image =  div.findElement(By.className("alc-img")).getAttribute("src");

System.out.println(image);

I never had luck using document.getElementsById('sc859')[0].getAttribute('src');" before. I always execute script directly like the following. Hope this is what you wanted. And, src does not exist on div rather on following img tag so your selector was wrong.

String src = (String) ((JavascriptExecutor)driver).executeScript("return document.querySelector(\"#sc859>img\").getAttribute(\"src\");");

System.out.println(src);

Print

data:image/gif;base64,R0lGODlhAQABAJAAAP///wAAACH5BAUQAAAALAAAAAABAAEAAAICBAEAOw==

不需要使用JavaScript,你也可以缩短Francesco的答案:

String src = driver.findElement(By.cssSelector("#sc859 > img.alc-img")).getAttribute("src");

There are 3 things ur doing wrong -

1 - getElementsById its getElementById which will return you only single element not a collection of it. There is no method getElementsById as far as i know.

2 - you are missing return in your executeScript method.

3 - There is no src attribute attached to div element whose id you have passed. src is attached to only img attribute.

So finally your code should be something like:

String imgeJs = jse.executeScript("return document.getElementById('sc859').childNodes[1].getAttribute('src')").toString();

or you can also achieve it by:

WebElement element = driver.findElement(By.cssSelector("#sc859" > img.alc-img));
String imgeJs = jse.executeScript("return arguments[0].getAttribute('src')", element).toString();

Or else follow rest of the answers where you can simply get it done by element.getAttribute("src") method of WebElement interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM