Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

How take a screenshot of a specific webelement using selenium and java

driver.findElement(By.xpath("//button[@id='e-dropdown-btn_16']")).click();
       List <WebElement>dropdownoptions=driver.findElements(By.xpath("//ul[@role='menu']/li"));
        for (WebElement value :dropdownoptions)
        {
            String valuetoselect=value.getText();
            
            if(valuetoselect.equalsIgnoreCase("Fit one page"))
            {
            value.click();
            }
           
         }
driver.wait(2000);
        WebElement element =driver.findElement(By.xpath("//div[@id='container_editor_viewerContainer']"));
        JavascriptExecutor js = (JavascriptExecutor) driver;
                   File a = new File("c:/a.png");
                  js.executeScript("arguments[0].scrollIntoView()",element); 
                  File b =element.getScreenshotAs(OutputType.FILE);
                  FileHandler.copy(b, a);
question from:https://stackoverflow.com/questions/66060256/how-take-a-screenshot-of-a-specific-webelement-using-selenium-and-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import java.io.File;
import java.nio.file.Files;
...
driver.get("https://youtube.com");
WebElement start = driver.findElement(By.cssSelector("div#start"));
File file = start.getScreenshotAs(OutputType.FILE);
Files.copy(file.toPath(), Path.of("/tmp/start.png"));

P.S. - The issue that might prevent your file to be saved is that you're trying to save it to root of C drive. Try to save it to some folder.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...