結合tkinter與opencv爬取豆瓣電影(2
先看下效果^ ^
嘻嘻

注:本片為上一篇文章實作爬取豆瓣電影的優化版
除源代碼外,其他皆與結合tkinter與opencv爬取豆瓣電影(1 相同
直接附上源代碼:
from tkinter import *
import tkinter as tk
from tkinter import ttk
import cv2
import os
import requests
from bs4 import BeautifulSoup
import re
import urllib.request,urllib.error
import PIL.Image,PIL.ImageTk
from PIL import Image, ImageTk
class Douban:
def __init__(self):
self.camera1 = None
self.camera2=None
self.root = Tk()
self.root.title('douban.movie')
self.root.geometry('1000x800')
self.root.iconbitmap('0.gif')
self.flag=False
self.len=0
self.first=True
self.root.configure(bg='yellow')
self.Douban_info()
mainloop()
def Douban_info(self):
global button3
self.Image_info1=Label(self.root,bg='red')
self.Image_info1.place(x=700,y=350)
self.Image_info2=Label(self.root,width=500,height=500,bg='red')
self.Image_info2.place(x=180,y=290)
self.url="".join(Data_info[i][1])
self.camera2=cv2.VideoCapture(self.url)
self.text=Text(self.root,width=25,height=15)
self.text.place(x=0,y=350)
Label(self.root,text='預告片資訊串列', fg='green', bg='yellow',font=('宋體', 15)).place(x=23,y=320)
Label(self.root,text='海 報 圖 片', fg='purple', bg='white',font=('宋體', 18)).place(x=780,y=315)
self.Movie_list()
self.Basic_info()
self.Poster_info()
self.button1=Button(self.root, width=8, height=2, text="上一部", bg="orange",font=("楷", 12),command=self.Prior_film).place(x=0, y=550)
self.button2=Button(self.root, width=8, height=2, text="下一部", bg="orange",font=("楷", 12),command=self.Next_film).place(x=90, y=550)
self.button3=Button(self.root, width=18, height=2, text="播放(暫停)", bg="blue",fg="white",font=("宋", 12),command=self.Start)
self.button3.place(x=0, y=650)
self.button4=Button(self.root, width=18, height=2, text="退出播放", bg="blue",fg="white",font=("宋", 12),command=self.Exit)
self.button4.place(x=0, y=700)
self.button5=Button(self.root, width=18, height=2, text="倍速播放", bg="blue",fg="white",font=("宋", 12),command=self.Speed)
self.button5.place(x=0, y=600)
def Next_film(self):
global i
if i>=len(Data_info):
return
else:
i+=1
self.len=0
self.first=True
self.camera2.release()
self.url="".join(Data_info[i][1])
self.camera2=cv2.VideoCapture(self.url)
self.Basic_info()
self.Image_info1.place_forget()
self.Poster_info()
def Prior_film(self):
global i
if i<=0:
return
else:
i-=1
self.len=0
self.first=True
self.camera2.release()
self.url="".join(Data_info[i][1])
self.camera2=cv2.VideoCapture(self.url)
self.Basic_info()
self.Image_info1.place_forget()
self.Poster_info()
def Basic_info(self):
self.text.delete('1.0','end')
self.text.tag_config("tag_1", backgroun="yellow", foreground="red")
self.text.tag_config("tag_2", backgroun="white", foreground="blue")
self.text.insert(END,"電影名: ","tag_1")
self.text.insert(END,str(Data_info[i][4])+"\n"+"\n","tag_2")
self.text.insert(END,"導演: ","tag_1")
self.text.insert(END,str(Data_info[i][5])+"\n"+"\n","tag_2")
self.text.insert(END,"主演: ","tag_1")
actors=Data_info[i][0]
for actor in actors:
self.text.insert(END,str(actor)+" ","tag_2")
self.text.insert(END,"\n"+"\n")
self.text.insert(END,"預告片鏈接:","tag_1")
self.text.insert(END,str(Data_info[i][3])+"\n"+"\n","tag_2")
self.text.insert(END,"海報鏈接:","tag_1")
self.text.insert(END,str(Data_info[i][2])+"\n"+"\n","tag_2")
def Save_poster(self,URL):
response=requests.get(URL)
Poster=os.path.join("D:/","poster")
self.File_path='{0}/{1}.{2}'.format(Poster,str(Data_info[i][4]),'jpg')
if not os.path.exists(self.File_path):
with open(self.File_path,'wb')as f:
f.write(response.content)
def Save_video(self,URL):
flag=True
response = requests.get(URL)
Video = os.path.join("D:/","video")
self.File_path='{0}/{1}.{2}'.format(Video,str(Data_info[i][4]),'mp4')
if not os.path.exists(self.File_path):
with open(self.File_path,'wb')as f:
flag=False
tk.messagebox.showinfo(title='下載電影', message='開始下載電影')
root=Tk()
root.geometry("800x150")
root.title('下載')
Label(root,text='電影正在下載中', fg='red', bg='yellow',font=('宋體', 30)).place(x=190,y=60)
cv=Canvas(root,bg='white',width=700,height=20)
cv.place(x=50,y=120)
cv=Canvas(root,bg='Lime',width=0,height=20)
cv.place(x=50,y=120)
for j in range(0,700):
cv['width']=j
root.update()
f.write(response.content)
root.destroy()
if flag:
tk.messagebox.showinfo(title='下載電影', message='檔案中已存在該電影')
else:
tk.messagebox.showinfo(title='下載電影', message='電影下載完畢')
def Poster_info(self):
self.Image_info2.place_forget()
self.Image_info1.place(x=700,y=350)
self.url1="".join(Data_info[i][2])
self.Save_poster(self.url1)
self.camera1=cv2.VideoCapture(self.url1)
Success,img=self.camera1.read()
if Success:
cv2image=cv2.cvtColor(img,cv2.COLOR_BGR2RGBA)
Current_image=Image.fromarray(cv2image)
imgtk=ImageTk.PhotoImage(image=Current_image)
self.Image_info1.imgtk=imgtk
self.Image_info1.config(image=imgtk)
def Film_info(self):
self.Save_video(self.url)
self.Loop_film()
def Loop_film(self):
cv1=Canvas(self.root,bg='white',width=790,height=10)
cv1.place(x=180,y=770)
self.cv=Canvas(self.root,bg='Lime',width=0,height=10)
self.cv.place(x=180,y=770)
self.Image_info2.place(x=180,y=290)
frame_count=self.camera2.get(7)
rate=self.camera2.get(5)
step=790/frame_count
self.len+=step
if self.len<=790:
self.cv['width']=self.len
Success,img=self.camera2.read()
if Success:
cv2image=cv2.cvtColor(img,cv2.COLOR_BGR2RGBA)
if not self.flag:
return
Current_image=Image.fromarray(cv2image)
imgtk=ImageTk.PhotoImage(image=Current_image)
self.Image_info2.imgtk=imgtk
self.Image_info2.config(image=imgtk)
self.root.after(24,lambda:self.Loop_film())
def Exit(self):
self.cv.place_forget()
self.camera2.release()
self.Image_info2.place_forget()
self.url="".join(Data_info[i][1])
self.camera2=cv2.VideoCapture(self.url)
self.root.update()
def Speed(self):
self.url="".join(Data_info[i][1])
self.camera2=cv2.VideoCapture(self.url)
self.flag=True
self.Loop_film()
def Start(self):
if self.first:
self.flag= not self.flag
self.button3['text']='暫停'
self.Film_info()
self.root.update()
self.first=False
else:
self.flag= not self.flag
if self.flag:
self.button3['text']='暫停'
self.Loop_film()
self.root.update()
else:
self.button3['text']='播放'
self.root.update()
def Movie_list(self):
Label(self.root,text='豆 瓣 電 影', fg='red', bg='yellow',font=('宋體', 30)).place(x=380,y=30)
self.checkDate=ttk.Treeview(self.root,column=('name'))
self.checkDate.heading('#0',text='電影序號')
self.checkDate.heading('name',text='電影名稱')
self.checkDate.column('name',width=800,anchor='center')
c=list(range(1,len(Data_info)+1))
d=[]
for index in range(0,len(Data_info)):
d.append(Data_info[index][4])
dict1 = dict(zip(c,d))
rowCount=1
self.checkDate.tag_configure("evenColor",background="LightBlue")
for index in dict1.keys():
if rowCount%2==0:
self.checkDate.insert("",'end',text=' '+str(index), values=dict1[index])
else:
self.checkDate.insert("",'end',text=' '+str(index), values=dict1[index],tags=("evenColor"))
rowCount+=1
yscrollbar = Scrollbar(self.root,orient=VERTICAL,command=self.checkDate.yview)
self.checkDate.configure(yscrollcommand=yscrollbar.set)
yscrollbar.pack(side=RIGHT,fill=Y)
self.checkDate.place(x=0,y=80)
def Click(event):
global i
self.camera2.release()
self.flag=True
i=int(self.checkDate.selection()[0][2:4])-1
self.url="".join(Data_info[i][1])
self.camera2=cv2.VideoCapture(self.url)
self.Loop_film()
self.Poster_info()
self.checkDate.bind('<<TreeviewSelect>>',Click)
class Clutch():
def __init__(self):
self.findLink=re.compile(r'<a class="ticket-btn" data-psource="poster" href="(.*?)" target="_blank">')
self.findImag=re.compile(r'<img.*?src="(.*?)".*?>',re.S)
self.findTitle=re.compile(r'<span property="v:itemreviewed">(.*)</span>')
self.finddirector=re.compile(r'<a href=".*?" rel="v:directedBy">(.*)</a>')
self.findActor=re.compile(r'<a\b href="[^"]*"[^>]*>([\s\S]*?)</a>',re.S)
self.findVideo=re.compile(r'<a\b[^>]+\bhref="([^"]*)"[^>]*>[\s\S]*?</a>',re.S)
self.findRealVideo=re.compile(r'<source src="(.*?)".*?>')
Douban_url="https://movie.douban.com/cinema/nowplaying/beijing/"
List_url=self.Get_url(Douban_url)
Data_info=self.Crawing(List_url)
def Get_url(self,Douban_url):
List_url=[]
html=self.Ask_url(Douban_url)
soup=BeautifulSoup(html,"html.parser")
for item in soup.find_all("li",class_="poster"):
item=str(item)
link=re.findall(self.findLink,item)
List_url.append(link)
return List_url
def Crawing(self,List_url):
for i in range(0,30):
print("爬蟲中……")
url="".join(List_url[i])
html=self.Ask_url(url)
soup=BeautifulSoup(html,"html.parser")
for item in soup.find_all('div',id="wrapper"):
data=[]
actors=[]
for item1 in item.find_all('a',rel="v:starring"):
item1=str(item1)
actor=re.findall(self.findActor,item1)
actors.append("".join(actor))
data.append(actors)
for item2 in item.find_all('li',class_="label-trailer"):
item2=str(item2)
video=re.findall(self.findVideo,item2)
urlvideo="".join(video)
htmlvideo=self.Ask_url(urlvideo)
soup_video=BeautifulSoup(htmlvideo,"html.parser")
for V in soup_video.find_all('div', class_="cont"):
V=str(V)
real_video=re.findall(self.findRealVideo,V)
data.append("".join(real_video))
for item3 in item.find_all('div',class_="subject clearfix"):
item3=str(item3)
img=re.findall(self.findImag,item3)
data.append("".join(img))
item=str(item)
data.append(url)
titles=re.findall(self.findTitle,item)
data.append("".join(titles))
director=re.findall(self.finddirector,item)
data.append("".join(director))
Data_info.append(data)
return Data_info
def Ask_url(self,url):
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.47" }
request=urllib.request.Request(url,headers=headers)
html=" "
try:
response=urllib.request.urlopen(request)
html=response.read().decode("utf-8")
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
return html
if __name__ == '__main__':
i=0
Data_info=[]
Clutch=Clutch()
Douban=Douban()
最后
如果你學到了知識,請毫不猶豫地點贊關注;如果你有問題,請毫不猶豫地在評論區說明你的問題,我來解決;如果你發現我有問題,那太好了,免費幫你查找各類電子書!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/240605.html
標籤:python
