0

I have a question how to download an image with selenium and save it to disk. the download itself I know how to do from a direct link src. I have a page that has an 'download image' button but I would like to use python to download it. The code responsible for downloading the image looks like this, it is not a direct reference with a url link to it.

function downloadPhoto() {
    data = {  };
    data.directory_id = '56899';
    data.fileName = 'k_000078.JPG';

    $.ajax({
        url: '/photo/request-link',
        data: data,
        type: 'post',
        dataType: 'json',
        async: false,
        success: function (response) {
            if (response.state == 'TRUE') {
                window.open('/photo/download');
            }
            else {
                $('div#alert').html(response.message);
                $('div#alert').dialog({ })
            }
        }
    })

}

Thank you in advance for your help

PYJTER
  • 79
  • 7

1 Answers1

2

you have a few options. But irst you need to find the photo in the web page. maybe by xpath.

from selenium import webdriver
driver = webdriver.Firefox()
driver.get(url)
with open('filename.png', 'wb') as file:
    file.write(driver.find_element_by_xpath(your_xpath).screenshot_as_png)

more option is by using urlib

import urllib
from selenium import webdriver

driver = webdriver.Firefox()
driver.get(url)

# get the image source
img = driver.find_element_by_xpath(xpath)
src = img.get_attribute('src')

# download the image
urllib.urlretrieve(src, "file.png")

driver.close()
Tal Folkman
  • 2,368
  • 1
  • 7
  • 21