selenium无头 加TK进度条学习
from selenium import webdriverfrom selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditionsasEC
import requests, time, tqdm,re
import tkinter as tk
fromtkinterimportttk
fromtkinter.filedialog importaskdirectory
fromselenium.webdriver.chrome.options importOptions
from threading import Thread
import functools
#配置无头
# 无头浏览器
chrome_options = Options()
# 增加无头
chrome_options.add_argument('--headless')
chrome_options.add_argument("--disable-gpu")
# 防止被网站识别
chrome_options.add_experimental_option('excludeSwitches',['enable_automation'])
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36',
}
def cal_back(func):
@functools.wraps(func)
def marge(*args):
t = Thread(target=func,args=(*args,))#第一个参数是线程函数变量,第二个参数args是一个数组变量参数,如果只传递一个值,就只需要i, 如果需要传递多个参数,那么还可以继续传递下去其他的参数,其中的逗号不能少,少了就不是数组了,就会出错。
print(func.__name__,"正在开启线程") #func.__name__获取 函数名字
t.start()
return marge
def get_url(url):
# 实例化浏览器对象
driver = webdriver.Chrome(executable_path=r'chromedriver.exe',chrome_options=chrome_options)
for i in range(3):
try:
driver.get(url)
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, "PLAYERS")))
iframe = driver.find_element_by_id("PLAYERS")
# 进入嵌套网页
driver.switch_to.frame(iframe)
wait.until(EC.presence_of_element_located((By.CLASS_NAME, "dplayer-video")))
mov_url = driver.find_element_by_class_name("dplayer-video").get_attribute('src')
if mov_url != "":
driver.quit()# 退出浏览器
return mov_url
else:
driver.quit()# 退出浏览器
time.sleep(2)
print("正在重新请求")
continue
except:
print("发生错误,正在重新请求")
driver.quit()# 退出浏览器
continue
# 请求函数
def html_response(url):
for i in range(3):
try:
resp = requests.get(url, headers=headers, stream=True, timeout=20)# stream=True表示请求成功后并不会立即开始下载,而是在调用iter_content方法之后才会开始下载
if resp.status_code == 200:
return resp
except Exception:
print(Exception)
time.sleep(2)
print("正在重新请求")
continue
# 添加进度条和下载
def mov_down(url):
path =ui.vv.get()
resp = html_response(url)
chunk_size = 40960# 设置每次下载的块大小
# 视频长度
file_size = int(resp.headers.get('Content-Length')) # 从返回的response的headers中获取文件大小
print(file_size)
ui.t.insert("insert", f"视频大小{file_size/(1024*1024)}M")
ui.t.insert("insert", "\n")
ui.t.see("end")
# 填充进度条
fill_line = ui.canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill="green")
raise_data = 500 / (file_size / chunk_size)# 增量大小,600为进度条的长度
# 初始化进度条长度
pbar = tqdm.tqdm(total=file_size)
with open(path+"/"+"电影下载.mp4", 'wb')asf:
n = 0
for chunk in resp.iter_content(chunk_size=chunk_size):
f.write(chunk)
pbar.set_description("正在下载中")# 设置修改进度条的描述。参数
pbar.update(chunk_size)# 手动更新进度条,对读取文件等流很有用
n = n + raise_data
ui.t.insert("insert", f"已经下载视频大小{n / (1024 * 1024)}M")
ui.t.insert("insert", "\n")
ui.t.see("end")
ui.canvas.coords(fill_line, (0, 0, n, 60))
root.update()
clean_progressbar()
ui.t.insert("insert","下载完成")
ui.t.insert("insert","\n")
ui.t.see("end")
# 清空进度条
def clean_progressbar():
# 清空进度条
fill_line = ui.canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill="white")
x = 500# 未知变量,可更改
n = 600 / x# 465是矩形填充满的次数
for t in range(x):
n = n + 600 / x
ui.canvas.coords(fill_line, (0, 0, n, 60))
root.update()
class mov_ui():
def __init__(self,root):
self.root =root
self.vv=tk.StringVar()
self.path1 = tk.StringVar()
def ui_cuaw(self):
# 标题
self.root.title("视频电影下载")
# 画布大小
self.root.geometry("600x480")
#标签
tk.Label(self.root,text="视频电影下载",font="楷体").place(x=250,y=10)
#搜索按钮
ttk.Button(self.root,text="视频电影网址").place(x=40,y=50)
#输入框
ttk.Entry(self.root,width=60,textvariable=self.path1).place(x=140,y=52)
#选择存放地址
ttk.Button(self.root, text="选择存放地址",command=self.mov_save).place(x=40, y=80)
ttk.Entry(self.root, width=60,textvariable=self.vv).place(x=140, y=82)
#状态文本框
tk.Label(self.root, text="下载状态").place(x=240, y=110)
ttk.Button(self.root, text="视频下载",command=main).place(x=40, y=110)
self.t=tk.Text(self.root, width=75,height=22)
self.t.place(x=40, y=140)
#进度条
self.canvas = tk.Canvas(self.root, width=530, height=16, bg="white")
self.canvas.place(x=38,y=440)
# 存放地址
def mov_save(self):
path = askdirectory()
path = re.sub(r"/", "\\\\", path)
self.vv.set(path)
@cal_back
defmain():
ui.t.delete("1.0","end")
jx_url = ui.path1.get()
if jx_url != "":
url = f"https://jx.aidouer.net/?url={jx_url}"
mov_url = get_url(url)
print(mov_url)
mov_down(mov_url)
print("下载完成")
else:
ui.t.insert("insert", "你还没入输入网址:")
ui.t.insert("insert", "\n")
ui.t.see("end")
if __name__ == '__main__':
#画布
root= tk.Tk()
#ui类
ui = mov_ui(root)
ui.ui_cuaw()
#循环
root.mainloop()
支持一个,试试好不好用! 大神牛鼻威武 不错的经验资料,学习了。
页:
[1]