Python-如何将图片下载到Windows上的特定文件夹位置?

我有这个脚本,可以从给定的网址下载所有图像:from selenium import webdriverimport urllibclass ChromefoxTest:def __init__(self,url):self.url=urlself.uri = []def chromeTest(self):# file_name = C:\Users\...

我有这个脚本,可以从给定的网址下载所有图像:

from selenium import webdriver
import urllib


class ChromefoxTest:

    def __init__(self,url):
        self.url=url
        self.uri = []

    def chromeTest(self):
       # file_name = "C:\Users\Administrator\Downloads\images"
        self.driver=webdriver.Chrome()
        self.driver.get(self.url)
        self.r=self.driver.find_elements_by_tag_name('img')
       # output=open(file_name,'w')

        for i, v in enumerate(self.r):
            src = v.get_attribute("src")
            self.uri.append(src)
            pos = len(src) - src[::-1].index('/')
            print src[pos:]
            self.g=urllib.urlretrieve(src, src[pos:])
          #  output.write(src)
       # output.close()


if __name__=='__main__':
    FT=ChromefoxTest("http://imgur.com/")
    FT.chromeTest()

我的问题是:如何使此脚本将所有图片保存到Windows计算机上的特定文件夹位置?

解决方法:

您需要指定要保存文件的路径. the documentation for urllib.urlretrieve中对此进行了解释:

该方法是:urllib.urlretrieve(url [,filename [,reporthook [,data]]]).
并且文档说:

The second argument, if present, specifies the file location to copy to (if absent, the location will be a tempfile with a generated name).

所以…

urllib.urlretrieve(src, 'location/on/my/system/foo.png')

将图像保存到指定的文件夹.

另外,考虑查看documentation for os.path.这些功能将帮助您操纵文件名和路径.

本文标题为:Python-如何将图片下载到Windows上的特定文件夹位置?

基础教程推荐