python的N个小功能(连接数据库并下载相应位置的图片)

##############################################################################################################连接数据库, mysqldb.py###########################

###############################################################################

# -*- coding: utf-8 -*-

"""

Created on Fri Mar 20 10:50:56 2015

 

@author:sl

"""

import os

import MySQLdb

 

MySQL_NAME = os.getenv('MySQL_NAME', 'aaa')

MySQL_USER = os.getenv('MySQL_USER', 'bbb')

MySQLPASSWORD = os.getenv('MySQL_PASSWORD', 'ccc')

MySQL_HOST = os.getenv('MySQL_HOST', 'ddd')

MySQL_PORT = os.getenv('MySQL_PORT','eee')

 

 

def connect():

    db=MySQLdb.connect(host=MySQL_HOST, user=MySQL_USER, passwd=MySQLPASSWORD, db=MySQL_NAME, charset="utf8")   

    return db

 

 

###############################################################################

#####################循环读取下载相应位置图片##################################

###############################################################################

 

# -*- coding: utf-8 -*-

"""

Created on Mon Mar 06 14:55:15 2017

 

@author:sl

"""

 

import mysqldb

#import datetime

import pandas as pd

db = mysqldb.connect()

sql='''

    SELECT

             aaa,

             bbb as urls

    FROM

             ccc

    GROUP BY

             aaa

'''

df = pd.read_sql(sql, con=db)

db.close()

 

 

from PIL import Image

from io import BytesIO

import requests

import os

from PIL import ImageFile

ImageFile.LOAD_TRUNCATED_IMAGES = True

 

def download_jpg(url, name):

    response = requests.get(url).content  ##########获取url对应内容

    img = Image.open(BytesIO(response)) ##########打开图片

    img.save(name)                   #########保存图片

 

if __name__ == '__main__':

    df1=df.set_index('aaa')       ####以第一列为index,第二列为内容

    for mulu in df['aaa']:         ####得到第一列全部内容并循环

        if not os.path.exists(r' E:\pp\%s'%(mulu)):

            os.makedirs(r' E:\pp\%s'%(mulu))

        for url in df1.loc[mulu]:   ####由第一列内容对应位置得到第二列内容

            #print url

            bb=url.split(',')

            lens=len(bb)

            for i in range(lens):

                download_jpg('http://aaa=%s'%(str(bb[i])),r'E:\pp\%s\%s.jpg'%(mulu,str(mulu)+str(i))) ######下载对应url区域图片,并以文件夹+序号命名

 

posted @ 2017-03-07 20:10  白鹭倾城  阅读(864)  评论(0编辑  收藏  举报