2017-09-20 76 views
-1

我使用Chrome作为我的浏览器,我想用Selenium将验证码保存到我的电脑中。每次我从URL请求时,我都会得到一个随机图像,但我需要浏览器上显示的图像,因此我无法再请求它(获取图像的src,然后再使用requests这样的另一个请求)获得不同的图像)如何使用Selenium和Python保存加载的图片资源?

拿这个网站为例(该网站我想验证码从具有白名单,所以我不能使用)。 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') 

现在我可以在浏览器中查看图片,然后我应该如何将相同的图片保存到我的电脑中作为文件?

P.S.

  • img.screenshot('image.png')在带有验证码的网站上无法正常工作。

  • 保存页面的整个屏幕截图,但请让我知道一个更好的解决方案。

+0

它看起来可能更容易采取截图,因为URL是相同的,但它会产生不同的图像每次。 [以前的建议](https://stackoverflow.com/questions/11893904/how-to-save-an-image-by-selecting-save-image-as-in-a-context-menu-using-sel) – Kyle

+0

请编辑该问题,将其限制为具有足够细节的特定问题以确定合适的答案。避免一次询问多个不同的问题。请参阅[问]页面以获得澄清此问题的帮助。 – JeffC

回答

0

我不确定Chrome,但我可以在Firefox浏览器上做同样的事情。 的代码是这样的:

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 
+0

忘记添加语句关闭浏览器。希望你会一起添加它。 – Akash

相关问题