user16334850
user16334850

Reputation:

How to download image using selenium

Hi I have picture on a page which has to be downloaded and then be used to import to another site.

whis is what the site looks

enter image description here

I want to download this using xpath and the xpath is //*[@id="word-img"]/img.

code of the picture looks like this

    <div id="word-img" style="width: 600px; height: 200px; margin-bottom: 20px; background: white;"><img src="https://10fastfingers.com/anticheat/generate_word_picture?rand=8644839612" alt=""></div>

<img src="https://10fastfingers.com/anticheat/generate_word_picture?rand=8644839612" alt="">

Upvotes: 1

Views: 5210

Answers (1)

Prophet
Prophet

Reputation: 33361

There are several ways to do that.
1.

import urllib

# get the image source
img = driver.find_element_by_xpath('//*[@id="word-img"]/img')
src = img.get_attribute('src')

# download the image
urllib.urlretrieve(src, "my_image.png")
with open('my_picture.png', 'wb') as file:
    file.write(driver.find_element_by_xpath('//*[@id="word-img"]/img').screenshot_as_png)

Upvotes: 2

Related Questions