Search code examples
pythonpython-2.7seleniumsendkeys

Saving Images from a URL in selenium (Python)


So, I finally completed my simple script to fetch some image links from some site. Now, the problem is that selenium isn't saving those images. No, I don't want screenshots, they are not serving the purpose. Screenshot leaves a lot of white space as it see in it's own resolution.

Anyways, I've tried this to send "ctrl+S" and then press "Enter" :

saveas = ActionChains(driver).key_down(Keys.CONTROL).send_keys('s').key_up(Keys.CONTROL).key_down(Keys.ENTER).key_up(Keys.ENTER)
        saveas.perform()

Now, what am I doing wrong here? the link to image : http://imgcomic.naver.net/webtoon/654817/44/20160314180903_2cfdd685f7e4f2c93a54e819898d6fb1_IMAG01_2.jpg


Solution

  • Webdriver takes whole page screenshot. However you can try by cropping the image as per your element dimensions. Below java code will helps you

     driver.get("http://www.google.com");
        WebElement image = driver.findElement(By.id("hplogo"));   
        //Get entire page screenshot
        File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        BufferedImage  fullImg = ImageIO.read(screenshot);
        //Get the location of element on the page
        Point point = image.getLocation();
        //Get width and height of the element
        int imageWidth = image.getSize().getWidth();
        int imageHeight = image.getSize().getHeight();
        //Crop the entire page screenshot to get only element screenshot
        BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), imageWidth,
                imageHeight);
        ImageIO.write(eleScreenshot, "png", screenshot);
        //Copy the element screenshot to disk
        FileUtils.copyFile(screenshot, new File("E:\\selenium_desk\\GoogleLogo_screenshot1.png"));
        driver.close();
    

    Thank You, Murali