摘要
論文介紹了利用python實現(xiàn)分割本地圖片熊经,爬取網(wǎng)站圖片的功能。該項目能夠自由選擇分割方式沉眶,以及選擇爬取圖片的類型双肤,完成此項目運(yùn)用了python中的tkinter,os,urllib等模塊,使用了python創(chuàng)建窗口帖烘,文件夾亮曹,點擊按鈕進(jìn)入其它文件等的功能。
[if !supportLists]一. [endif]引言秘症。
現(xiàn)在Python擁有許多模塊照卦,只要調(diào)用模塊內(nèi)容,就能很簡便的寫出一些功能乡摹。
我設(shè)計了一款關(guān)于圖片分割役耕,下載的小工具,不用PS這些軟件聪廉,就能輕松的分割圖片瞬痘,下載圖片也不用一張張圖片慢慢下載,只要輸入關(guān)鍵字就能下載相關(guān)圖片板熊。
[if !supportLists]二.??[endif]系統(tǒng)結(jié)構(gòu)图云。
系統(tǒng)結(jié)構(gòu)圖
? ??
系統(tǒng)流程圖流程圖
[if !supportLists]三.[endif]實現(xiàn)代碼。
1邻邮、設(shè)置一個窗口:
? ??? 2、設(shè)置背景圖片:
3克婶、按鈕的設(shè)置:
1筒严、先創(chuàng)建個分割圖片的函數(shù)
一開始使用的是指定圖片,這是之后完全的
2情萤、創(chuàng)建函數(shù)鸭蛙,用來選擇要分割的圖片:
3、按鈕來觸發(fā)事件:
就是爬取百度圖片筋岛,模仿于網(wǎng)上各位大佬的娶视,大家可去看看,文章來自:
https://blog.csdn.net/hust_bochu_xuchao/article/details/79431145
[if !supportLists]1、 [endif]查看百度圖片源碼
查看源碼時肪获,點擊下一頁發(fā)現(xiàn)只有pn和gsm發(fā)生了變化
到目前為止寝凌,我知道的是:pn參數(shù)代表的是頁數(shù);word參數(shù)自然是關(guān)鍵詞孝赫,需要轉(zhuǎn)換編碼格式较木。
所以,可以拼接出page請求的URL青柄,代碼如下:
[if !supportLists]2伐债、 [endif]找到網(wǎng)頁中的圖片地址
·右鍵 查看網(wǎng)頁源代碼,然后點擊那些分類致开,就是男女類似的關(guān)鍵詞峰锁,然后就能獲取如圖下
·雙擊Name下面的網(wǎng)址后即可打開,分析JSON數(shù)據(jù)可知双戳,發(fā)現(xiàn)一張圖片有4種URL:fromURL,middleURL,thumbURL,objURL,前三種有反爬措施虹蒋,因此采用objURL.其中的字段objURL,即表示了原圖的下載地址拣技。
但是objURL是經(jīng)過加密的數(shù)據(jù)千诬,需要經(jīng)過解密才能正常使用,關(guān)于objURL解密可以看博文http://7dwww.com/article/36.html膏斤。
·根據(jù)URL地址徐绑,得到圖片地址的代碼為:
3、下載圖片并保存
(四)完整代碼
from tkinter import *
import os
#窗口設(shè)置
root =Tk()
root.geometry("1920x1080")#窗口大小
root.title("圖片下載分割")#窗口標(biāo)題
#背景圖片
photo =PhotoImage(file="index.gif")
theLabel = Label(root,
??????????????????? justify=LEFT,#對齊方式
??????????????????? image=photo,#加入圖片
??????????????????? compound = CENTER,#字體在圖片前顯示
??????????????????? fg = "white")#前景色
def image():
??? os.system("python image.py")
def download():
??? os.system("python download.py")
#按鈕組件
#按鈕的名字莫辨,字體傲茄,大小,顏色沮榜,按鈕事件
B1 = Button(root,text="分割圖片", font=("宋體",12), width=16,heigh=4, bg="#906b73", command=image)
B2 = Button(root,text="下載圖片", font=("宋體",12),width=16,heigh=4, bg="#906b73",command=download)
#按鈕位置
B1.place(relx=0.2,rely=0.5,anchor="center")
B2.place(relx=0.8,rely=0.5,anchor="center")
theLabel.pack()
root.mainloop()
from PIL import Image
from PIL import *
from tkinter importTk,mainloop,Label,Place
from tkinter import Button,Entry
from tkinter import filedialog
import os
root = Tk()
root.geometry("200x200")
'''
def num():
??? Label(root ,text="平行分割").grid(row = 0,column=0)
??? Label(root ,text="豎直分割").grid(row = 1,column=0)
??? e1= Entry(root)
??? e2= Entry(root)
??? e1.grid(row= 0,column=1,padx=10,pady=5)
??? e2.grid(row= 1,column=1,padx=10,pady=5)
??? m= e1.get()
??? n= e2.get()?
??? return m,n
'''
#選擇圖片
def callback():
??? fileName = filedialog.askopenfilename()
??? return fileName
def break_up():
??? #image = '1.jpg'
??? #獲得函數(shù)返回值
??? filename = callback()
#??? res = num()
#??? m = res([0])
#??? n = res([1])
??? img = Image.open(filename)
??? #在工作目錄創(chuàng)建文件夾用來存放分割的圖片
??? o = os.path.exists('fen')
??? if o==0:
??????? os.mkdir('fen')
??? os.chdir('fen')
??? size = img.size
??? #print(size)
??? #分割方式
??? n=int(input("請輸入平行分割塊數(shù):"))
??? m=int(input("請輸入豎直分割塊數(shù):"))
??? #準(zhǔn)備將圖片切割成m*n張小圖片
??? weight = int(size[0] // n)
??? height = int(size[1] // m)
??? #切割后的小圖的寬度和高度
??? #print(weight, height)
??? for j in range(n):
??????? for i in range(m):
??????????? box = (weight * i, height * j,weight * (i + 1), height * (j + 1))
??????????? region = img.crop(box)
??????????? region.save('分割_{}{}.png'.format(j, i))#保存圖片
#but1=Button(root,text='確定',command=num).pack()
#按鈕的設(shè)置
but2=Button(root,text='選擇圖片',command=break_up)
but2.place(relx=0.5,rely=0.5,anchor="center")
mainloop()
# coding=utf-8
"""根據(jù)搜索詞下載百度圖片"""
import re
import sys
import urllib
import os
import requests
import random
from tkinter importTk,mainloop,Label,Place,Entry,Button
def getPage(keyword,page,n):
??? page=page*n
??? keyword=urllib.parse.quote(keyword,safe='/')
??? url_begin="http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word="
??? url = url_begin+ keyword +"&pn=" +str(page) +"&gsm="+str(hex(page))+"&ct=&ic=0&lm=-1&width=0&height=0"
??? #代理IP
??? proxies =['101.254.136.130:443','114.234.80.188:9000']
??? proxy = random.choice(proxies)
??? proxy_support =urllib.request.ProxyHandler({'http':proxy})
??? opener =urllib.request.build_opener(proxy_support)
??? urllib.request.install_opener(opener)
??? return url
def get_onepage_urls(onepageurl):
??? try:
??????? html = requests.get(onepageurl).text
??? except Exception as e:
??????? print(e)
??????? pic_urls = []
??????? return pic_urls
??? pic_urls = re.findall('"objURL":"(.*?)",',html, re.S)
??? return pic_urls
def down_pic(pic_urls):
??? """給出圖片鏈接列表, 下載所有圖片"""
??? o = os.path.exists('pict')
??? if o==0:
??????? os.mkdir('pict')
??? os.chdir('pict')
??? for i, pic_url in enumerate(pic_urls):
??????? try:
?????????? ?pic = requests.get(pic_url, timeout=15)
??????????? string =str(i + 1) + '.jpg'
??????????? with open(string,'wb') as f:
??????????????? f.write(pic.content)
??????????????? print('成功下載第%s張圖片: %s'% (str(i + 1), str(pic_url)))
??????? except Exception as e:
??????????? print('下載第%s張圖片時失敗:%s' % (str(i + 1), str(pic_url)))
??????????? print(e)
??????????? continue
'''
root = Tk()
root.geometry("100x100")
Label(root ,text="輸入關(guān)鍵字下載").grid(row = 0,column=0)
e1= Entry(root)
e1.grid(row= 0,column=1,padx=10,pady=5)
w= e1.get()???
but2=Button(root,text='確定',command=root.quit)
but2.grid(row=1,column=0,padx=10,pady=5)
'''
if __name__ == '__main__':
??? w= input("請輸入關(guān)鍵詞:")
??? keyword = w?#關(guān)鍵詞, 改為你想輸入的詞即可, 相當(dāng)于在百度圖片里搜索一樣
??? page_begin=0
???page_number=30
??? image_number=3
??? all_pic_urls = []
??? while 1:
??????? if page_begin>image_number:
??????????? break
??????? print("第%d次請求數(shù)據(jù)",[page_begin])
???????url=getPage(keyword,page_begin,page_number)
??????? onepage_urls= get_onepage_urls(url)
??????? page_begin += 1
??????? all_pic_urls.extend(onepage_urls)
??? down_pic(list(set(all_pic_urls)))
mainloop()
[if !supportLists]四.[endif]實驗盘榨。
[if !supportLists]五.[endif]總結(jié)和展望。
總結(jié):該小工具是吧兩個小功能合在一起蟆融,說起來也不復(fù)雜草巡,比較難的還是第二個爬取圖片的操作,一開始我是在小甲魚視頻里學(xué)的型酥,但以前能爬的網(wǎng)站現(xiàn)在可能有改變了山憨,需要自己改下操作。還有小工具還有不足之處弥喉,就是連續(xù)選擇分割圖片時會不停在里面創(chuàng)建文件夾放分割圖片郁竟,有的圖片會爬取失敗。
參考文章:
[1]? https://www.cnblogs.com/loyolh/p/12313210.html
[2] https://blog.csdn.net/hust_bochu_xuchao/article/details/79431145