Python 批量下载图片脚本

import requests
import os


class PicFactory:
    menuName = "pictures"

    def __init__(self, host, numLen, startNum, stopNum):
        self.host = host
        self.numLen = numLen
        self.startNum = startNum
        self.stopNum = stopNum

    def run(self):
        try:
            os.makedirs(self.menuName)
        except FileExistsError:
            print("{0} 目录已存在".format(self.menuName))
        for i in range(self.startNum, self.stopNum + 1):
            length = len(str(i))
            imgUrl = self.host + self.getImgNo(length) + str(i) + ".jpg"
            html = requests.get(imgUrl)
            with open("{0}/{1}.jpg".format(self.menuName, str(i)), 'wb') as file:
                print("downLoading >>>>>>> {0} | {1}/{2}".format(imgUrl, self.stopNum, i))
                file.write(html.content)

    def getImgNo(self, length):
        imgNo = ""
        for i in range(1, self.numLen - length + 1):
            imgNo = imgNo + "0"
        return imgNos

使用说明 :

“http://xxx.com/001.jpg”

“http://xxx.com/010.jpg”

picInstance = PicFactory(
    host="http://xxx.com/",
    numLen=3,
    startNum=1,
    stopNum=10
)
picInstance.run()

voidm

在黑暗中支撑和平的无名者

2 Comments

留下你的评论

*评论支持代码高亮<pre class="prettyprint linenums">代码</pre>

相关推荐