收到一个任务:把上传到网上的图片下载下来并打印出来。
一个人四张图片,四百多个人,如果手动一张张下载的话估计几天都做不完,而且下载完后还要按人整理打印出来,排版都要累死人。
如果真要手动操作的话真是白读了这么多书了,是时候祭出python了。
以下只用到简单的爬虫,因为网页登陆需要输入验证码,所以我先网页登陆再用python获取cookie登陆(这网站安防设施一般情况),图片拼接排版用的是PIL模块,以前不知道这个模块这么好用,
import requests
import re
import PIL.Image as Image
import pandas as pd
from io import BytesIO
def catch_image(code):
#先在网页上通过F12查看网页的network,观察url的规律,一般都是有规律的,顺便复制请求头和cookie,其实也可以直接文件读取。
url="xxx"+code+"xxxxx"
heads={
"User-Agent":"Mozilla/5.0 (Windows NT 6.1) xxxxxxxx",
"Cookie":"SESSION=xxxxxxxxxxx;JSESSIONID=xxxxxxxxxxxxx",
"Connection":"close"}
response=requests.get(url,headers=heads).text
#直接用正则表达式,没有用lxml解析
image=re.findall('''<img\salt=""\ssrc="(.*?)"''',response,re.S)
named=re.findall("xxxxx.*?<td>(.*?)</td>",response,re.S)
ima_names=["xx","xx","xx","xx"]
w=1560
h=720
to_image=Image.new("RGB",(2*w,2*h))
axiss=[(0,0),(0,h),(w,0),(w,h)]
for i in range(0,4):
try:
#图片路径是不完整的,需要F12看具体路径来拼接。
download_image=requests.get("xxxxx"+image[i],headers=heads).content
buffer_image=BytesIO(download_image)
rom_image=Image.open(buffer_image).resize((w,h))
to_image.paste(rom_image,axiss[i])
#with open("./xxxx/{}-{}.jpg".format(named[0],ima_names[i]),"wb") as f:
#f.write(download_image)
except Exception as e:
continue
to_image.save("./拼接图/{}.jpg".format(named[0]))
def get_list():
df=pd.read_excel("./xxxxxxxx.xlsx")
return list(df["xxx"])
if __name__=="__main__":
sh_list=get_list()
i=1
for l in sh_list:
l=str(l)
print("正在下载第{}个---".format(i))
catch_image(l)
i+=1