Python 程序下载经办人照片
进行图片下载,需要提前准备好下载图片的存放文件夹;
python在与文件、目录打交道时,少不了os模块。os模块包含普遍的操作系统功能。
os.path.exists(filepath)——检验指定的对象是否存在;os.mkdir(filepath)——创建目录;os.path.join(path, name)——连接目录和文件名
1 import os 2 import sys 3 4 #city_id = sys.argv[1] 5 city_id = 660 6 7 def check_make_image_floder(filepath): 8 if not os.path.exists(filepath): 9 os.makedirs(filepath) 10 image_floder = "C:\\Users\\admin\\Desktop\\%s" %city_id 11 check_make_image_floder(image_floder)
urllib.urlretrieve(url, filename)—将远程数据下载到本地指定路径
1 import os 2 import sys 3 import urllib 4 5 #city_id = sys.argv[1] 6 city_id = 660 7 8 def check_make_image_floder(filepath): 9 if not os.path.exists(filepath): 10 os.makedirs(filepath) 11 image_floder = "C:\\Users\\admin\\Desktop\\%s" %city_id 12 check_make_image_floder(image_floder) 13 14 filename = "660170120991757571.jpg" 15 dest_dir = os.path.join(image_floder,filename) 16 17 url_example = 'http://xxx.xxx.xx.xxx:xxxx/REST/docService?timestamp=1450063392000&organId=xxxxx&busiType=1&appId=crmlog&staffNo=xxTEST200&filename=660/16000004/13298809/660170120991757571.jpg&method=get&password=crmlog1452&latnId=660&signature=731ccc37de5e48dc69bb9ba3xxxxxxxxx&version=001' 18 def crawl_image(url_example,dest_dir): 19 urllib.urlretrieve(url_example,dest_dir) 20 21 crawl_image(url_example,dest_dir)
进行文件下载前,先替换latnId;
1 import os 2 import sys 3 import urllib 4 import re 5 6 #city_id = sys.argv[1] 7 city_id = 660 8 9 url_example = 'http://xxx.xxx.xx.xxx:xxxx/REST/docService?timestamp=1450063392000&organId=2222&busiType=1&appId=crmlog&staffNo=xxTEST200&filename=663/16000004/13298809/6601701209917xxxxx.jpg&method=get&password=crmlog1452&latnId=663&signature=731ccc37de5e48dc69bb9ba34b9f3188&version=001' 10 pattern = re.compile(r'latnId=\d{2,3}') 11 image_url01 = re.sub(pattern, 'latnId='+str(city_id).strip(), url_example) 12 13 def check_make_image_floder(filepath): 14 if not os.path.exists(filepath): 15 os.makedirs(filepath) 16 image_floder = "C:\\Users\\admin\\Desktop\\%s" %city_id 17 check_make_image_floder(image_floder) 18 19 def crawl_image(image_url,dest_dir): 20 urllib.urlretrieve(image_url,dest_dir) 21 22 with open("C:\\Users\\admin\\Desktop\\%sdata.txt"%city_id,'r') as f: 23 lines = f.readlines() 24 lists = image_url01.split('&') 25 for list in lists: 26 if list.startswith('filename'): 27 for line in lines: 28 image_url02 = re.sub(list, 'filename='+line.strip(), image_url01) 29 results = line.split('/') 30 image_name_ex = results.pop() 31 image_info = urllib.urlopen(image_url02.strip()) 32 if image_info.getcode() == 200: 33 image_url = image_url02.strip() 34 dest_dir = os.path.join(image_floder,image_name_ex.strip()) 35 crawl_image(image_url,dest_dir) 36 print image_url + " write sucess !"