Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Selenium和Python保存加载的图片资源?_Python_Selenium_Selenium Webdriver_Selenium Chromedriver - Fatal编程技术网

如何使用Selenium和Python保存加载的图片资源?

如何使用Selenium和Python保存加载的图片资源?,python,selenium,selenium-webdriver,selenium-chromedriver,Python,Selenium,Selenium Webdriver,Selenium Chromedriver,我使用Chrome作为浏览器,我想用Selenium将验证码保存到我的计算机上。每次我从URL请求时,我都会得到一个随机图像,但我需要浏览器上显示的图像,这样我就不能再请求它了。(获取图像的src,然后发出另一个请求,如使用请求将得到不同的图像。) 以该网站为例(我想获取验证码的网站有一个白名单,因此我无法使用该白名单): 现在我可以在浏览器中看到图片了,那么我应该怎么做才能将相同的图片作为文件保存到我的计算机中 附言 img.screenshot('image.png')在带有验证码的网站

我使用Chrome作为浏览器,我想用Selenium将验证码保存到我的计算机上。每次我从URL请求时,我都会得到一个随机图像,但我需要浏览器上显示的图像,这样我就不能再请求它了。(获取图像的src,然后发出另一个请求,如使用
请求
将得到不同的图像。)

以该网站为例(我想获取验证码的网站有一个白名单,因此我无法使用该白名单):

现在我可以在浏览器中看到图片了,那么我应该怎么做才能将相同的图片作为文件保存到我的计算机中

附言

  • img.screenshot('image.png')
    在带有验证码的网站上不起作用

  • 保存整个页面截图是可行的,但请告诉我一个更好的解决方案


我对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

这将获得元素的屏幕截图

driver.find_element_by_css_selector('element selector here').screenshot_as_png

看起来截图可能更容易,因为url是相同的,但每次都会生成不同的图像。请编辑问题,将其限制为特定问题,并提供足够详细的信息,以确定适当的答案。避免同时问多个不同的问题。请参阅页面以获取澄清此问题的帮助。忘记添加语句以关闭浏览器。希望你能加上它。
driver.find_element_by_css_selector('element selector here').screenshot_as_png