参考上一个文章,使用免登录及插件。
加载cookiese,更新cookies,防止一直登录的烦人情况。使用已经安装的插件,更好的操作。-CSDN博客
需要配合插件自动下载。
原理,找开音频管理。然后会依次点击每一页上的音频,然后插件会自动下载。再自己写一个改名软件就可以了。
完整代码如下,完全可用。 因为我最多有100个每个专辑,如果你有特殊,你再修改即可。
代码如下:
import tkinter as tk
import random
from tkinter import filedialog
from datetime import datetime
import pyperclip
import os
import re
from tkinter import messagebox
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.common.exceptions import NoSuchElementException,ElementClickInterceptedException
from selenium.common.exceptions import WebDriverException
import json
import time
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import configparser
def js_condition(driver):
"""自定义等待条件函数,检查JavaScript返回值"""
return driver.execute_script("return document.readyState") == "complete"
def open_edge_browser(url):
global driver
# 设置Edge选项
edge_options = Options()
edge_options.use_chromium = True
# 向Edge浏览器传递启动参数
# edge_options.add_argument('--disable-extensions') # 禁用浏览器扩展
edge_options.add_argument('--disable-gpu') # 禁用GPU硬件加速
# 设置扩展的路径
extension_path = 'D:\\edge_adds\\0.0.8_0.crx'
# 添加扩展到 Options
edge_options.add_extension(extension_path)
driver = webdriver.Edge(options=edge_options)
# 定义 cookies 文件路径
cookies_file_path = 'aigccookies.txt'
# 检查 cookies 文件是否存在
if os.path.exists(cookies_file_path):
# 如果存在,读取文件内容
with open(cookies_file_path, 'rb') as file:
cookies = file.read()
# 将 cookies 加载到 WebDriver 中
driver.execute_cdp_cmd("Network.setCookies", {
"cookies": eval(cookies) # 使用 eval 解析 cookies 数据
})
# 接下来可以访问需要登录的页面,如果 cookies 有效,将实现免登录
driver.get(url) # 替换为实际的目标网页 URL
driver.maximize_window()
# 保存 cookies
cookies = driver.get_cookies()
with open('aigccookies.txt', 'w') as file:
file.write(str(cookies))
print("aigccookies已更新")
return driver
else:
print("Cookies 文件不存在,无法实现免登录。")
try:
# 打开网页
driver.get(url)
# 设置显式等待,等待页面加载完成
# 这里使用了多个条件来确保页面加载完成:
# 1. `EC.presence_of_element_located((By.TAG_NAME, 'body'))` 确保body标签存在,基本的HTML结构已加载。
# 2. `EC.visibility_of_element_located((By.ID, 'someId'))` 可以替换为页面上某个关键元素的ID,确保该元素不仅加载而且可见。
# 3. `EC.javascript_returned_value(True)` 可以用来执行JavaScript检查`document.readyState`是否为"complete"。
# 通常选择其中一个或几个条件根据实际情况而定,这里以`document.readyState`为例。
WebDriverWait(driver, 10).until(js_condition)
print("网页已加载完成。")
# # 等待页面加载完成
# driver.implicitly_wait(20) # 这里设置一个较短的隐式等待,以避免页面未完全加载
# 使用显式等待等待特定的 img 元素出现
try:
xpath = "// button[contains(., '上传作品')]"
user_info_img = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.XPATH, xpath))
)
# 确认元素加载完成
if user_info_img:
print("上传已定位:", user_info_img)
# 保存 cookies
cookies = driver.get_cookies()
with open('aigccookies.txt', 'w') as file:
file.write(str(cookies))
print("aigccookies已保存")
return driver
# 这里可以添加其他操作,例如获取元素的属性或执行点击等
except TimeoutException:
print("在等待时间内,元素未出现")
except Exception as e:
print(f"页面加载超时或发生错误: {e}")
def get_urls():
# 循环数字 1 到 10
for i in range(1, 11):
print("外循环:",i)
if i<=1:
pass
else:
try:
# 查找按钮
button = driver.find_element(By.CSS_SELECTOR, 'button.btn-next')
# 检查按钮是否被禁用
if button.get_attribute('disabled'):
print("按钮已被禁用,停止点击")
break
else:
# 如果按钮可用,执行点击操作
button.click()
except NoSuchElementException:
# 如果找不到按钮,打印消息并跳出循环
print("找不到按钮,停止尝试")
break
except WebDriverException as e:
# 如果发生 WebDriver 异常,打印错误并跳出循环
print(f"发生 WebDriver 异常: {e}")
break
# 点击按钮
button.click()
# # 使用 XPath 定位包含当前数字的 <li> 元素
# element = driver.find_element(By.XPATH, f'//li[@class="number" and text()="{i}"]')
# # 检查元素是否已经包含 'active' 类
# if 'active' not in element.get_attribute('class').split():
# # 使用 JavaScript 给元素添加 'active' 类
# driver.execute_script("arguments[0].classList.add('active');", element)
# # 使用 JavaScript 给元素添加 'active' 类
# driver.execute_script("arguments[0].classList.add('active');", element)
time.sleep(3)
for ii in range(1, 11):
# 使用 XPath 定位包含当前数字的 <li> 元素
now=(i-1)*10+ii
print("内循环:",now)
xpath_expression = f'//span[@class="item-index-text" and text()="{now}"]'
try:
# 等待元素出现,直到它可以被点击
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, xpath_expression))
)
# 使用 ActionChains 来模拟鼠标悬停和点击
action = ActionChains(driver)
action.move_to_element(element).pause(1).click().perform() # 暂停1秒后点击
except TimeoutException:
# 捕获超时异常,当元素在指定时间内未出现时
print(f"在指定的等待时间内未找到元素: {xpath_expression}")
except WebDriverException as e:
# 捕获 WebDriver 相关的其他异常
print(f"发生 WebDriver 异常: {e}")
# 点击该元素
# element.click()
def main():
window = tk.Tk()
window.title("donw_mp3")
window.geometry("500x300")
# # 创建按钮
# button_create = tk.Button(window, text="建立工作目录", command=create_work_directory)
# button_create.pack()
# 创建按钮
button_open = tk.Button(window, text="准备浏览器环境", command=lambda: open_edge_browser("https://mp.tencentmusic.com/login"))
button_open.pack()
button_read = tk.Button(window, text="先把页面调整好", command=get_urls)
button_read.pack()
#
# # 创建按钮
# button_get_answers = tk.Button(window, text="开始工作", command=lambda: autocomplete_tasks())
# button_get_answers.pack()
# # 测试按钮
# button_test = tk.Button(window, text="测试", command=lambda: test())
# button_test.pack()
window.mainloop()
if __name__ == "__main__":
main()
多余代码忽略。