Reputation: 31
I am using Chrome as my browser, and I want to save a captcha to my computer with Selenium. Every time I request from the URL, I get a random image, but I need the one that is displayed on the browser so I can't request for it again.(Getting the src of the image then make another request like using requests
will get a different image.)
Take this website as an example (The website I want to get the captcha from has a whitelist so I can't use that): https://unsplash.it/200/300/?random
from selenium import webdriver
if __name__ == '__main__':
driver = webdriver.Chrome(r'F:\Dev\ChromeDriver\chromedriver.exe')
driver.get('https://unsplash.it/200/300/?random')
img = driver.find_element_by_tag_name('img')
Now I can see the picture in the browser, then what should I do to save the same picture to my computer as a file?
P.S.
img.screenshot('image.png')
doesn't work on the website with the captcha.
Saving the whole screenshot of the page works, but please let me know a better solution.
Upvotes: 2
Views: 6890
Reputation: 21231
This will get you element's screenshot
driver.find_element_by_css_selector('element selector here').screenshot_as_png
Upvotes: 2
Reputation: 110
I am not sure about Chrome, but I was able to do the same on Firefox browser. The code goes like this:
from selenium import webdriver
import requests
driver=webdriver.Firefox()
driver.get("http/https://your website")
img=driver.find_element_by_xpath("xpath leading to your element")#locating element
src=img.get_attribute('src')#fetch the location of image
img=requests.get(src)#fetch image
with open('image.jpg','wb') as writer:#open for writing in binary mode
writer.write(img.content)#write the image
Upvotes: 0