Selenium实现CSDN自动关注

zjk 发布于 2024-02-22 184 次阅读


没有运行环境的可以参考这篇: https://www.jinke.love/4753.html

功能演示

完整代码

代码使用Python3编写的自动关注程序,使用了Selenium和Tkinter库,还使用多线程处理关闭浏览器和结束Tkinter应用程序。
程序打开浏览器并访问特定网站,并与网页交互,点击按钮和滚动页面。使用Tkinter创建右下角弹出窗口,显示操作结果。程序使用多线程,一个线程运行Selenium和Tkinter任务,另一个线程负责主Tkinter窗口。
使用此源码时,需要下载安装好谷歌浏览器,并且使用谷歌浏览器登录好CSDN账号,再将源码浏览器缓存路径改为自己的浏览器缓存路径。

import threading
import time
import tkinter as tk
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class PopupWindow:
    def __init__(self, master):
        self.master = master
        self.popup = tk.Toplevel()
        self.popup.wm_overrideredirect(True)  # 隐藏窗口边框和标题栏
        self.popup.wm_attributes('-topmost', 1)  # 窗口置顶
        self.popup_frame = tk.Frame(self.popup)
        self.popup_frame.pack()
        self.popup_text = tk.Text(self.popup_frame, wrap='word')
        self.popup_text.pack(side='left', fill='both', expand=True)
        self.scrollbar = tk.Scrollbar(self.popup_frame, command=self.popup_text.yview)
        self.scrollbar.pack(side='right', fill='y')
        self.popup_text.config(yscrollcommand=self.scrollbar.set)
        self.set_window_position()
    def set_window_position(self):
        screen_width = self.master.winfo_screenwidth()
        screen_height = self.master.winfo_screenheight()
        window_width = 200
        window_height = 100
        self.popup.geometry(
            f'{window_width}x{window_height}+{screen_width - window_width - 10}+{screen_height - window_height - 10}')
    def update_content(self, message):
        self.popup_text.insert('end', message + '\n')
        self.popup_text.see('end')  # 滚动到最底部
def getTab(driverObj):
    div_element = WebDriverWait(driverObj, 10).until(
        EC.visibility_of_element_located((By.CLASS_NAME, 'blog-nav-box'))
    )
    action = ActionChains(driverObj)
    action.move_to_element(div_element).perform()
    # 找到div元素下的所有a标签
    a_elements = div_element.find_elements(By.TAG_NAME, 'a')
    return [tabname.text for tabname in a_elements]
def changeTab(driverObj, tabName, popupWindow):
    try:
        parent_div = WebDriverWait(driverObj, 5).until(
            EC.visibility_of_element_located((By.CLASS_NAME, 'blog-nav-box')))
        action = ActionChains(driverObj)
        action.move_to_element(parent_div).perform()
        top_tab = WebDriverWait(driverObj, 5).until(
            EC.element_to_be_clickable((By.XPATH, f'//a[text()="{tabName}"]')))
        action.move_to_element(top_tab).click().perform()  # 模拟鼠标移动到顶部标签并点击
    except TimeoutException:
        return
def followUser(driverObj, tabName, popupWindow):
    try:
        fnum = 0
        sipder = WebDriverWait(driverObj, 5).until(EC.visibility_of_element_located((By.CLASS_NAME, 'template-cont')))
        if not sipder:
            return
        recommendations = WebDriverWait(driverObj, 5).until(
            EC.presence_of_all_elements_located((By.CLASS_NAME, 'recommendation')))
        for recommendation in recommendations:
            follow_button = recommendation.find_element(By.CLASS_NAME, 'recommendation-btn')
            if 'active' not in follow_button.get_attribute('class'):
                follow_button.click()
                fnum += 1
        popupWindow.update_content(f'{tabName}关注量:{fnum}')
    except Exception as e:
        popupWindow.update_content(f'{tabName}侧栏未显示')
        return
def run_selenium_and_tkinter(popupWindow):
    options = webdriver.ChromeOptions()
    options.add_argument('--start-maximized')
    options.add_argument('user-data-dir=C:\\Users\zhangjinke\AppData\Local\Google\Chrome\\User Data')
    options.add_experimental_option('detach', True)
    driver = webdriver.Chrome(options=options)
    driver.get('https://blog.csdn.net')
    tablist = getTab(driver)
    # 其他代码保持不变
    try:
        for tabname in tablist:
            popupWindow.update_content('当前标签页: ' + tabname)
            changeTab(driver, tabname, popupWindow)
            followUser(driver, tabname, popupWindow)  # 将tabName传递给followUser
            # time.sleep(1)
            driver.execute_script('window.scrollTo(0, 0)')
    finally:
        # 关闭浏览器并结束所有进程
        close_all_processes(driver, root, popupWindow.popup)
def close_all_processes(driver, root, popup):
    driver.quit()  # 关闭浏览器
    root.destroy()  # 结束Tkinter主窗口
    popup.destroy()  # 关闭提示窗口
if __name__ == '__main__':
    root = tk.Tk()
    root.withdraw()  # 隐藏Tkinter主窗口
    popup_window = PopupWindow(root)
    # 创建线程来运行Selenium和Tkinter
    selenium_thread = threading.Thread(target=run_selenium_and_tkinter, args=(popup_window,))
    selenium_thread.start()
    popup_window.update_content('主任务启动成功')
    root.protocol('WM_DELETE_WINDOW', lambda: [root.destroy(), popup_window.popup.destroy()])  # 处理窗口关闭事件
    root.mainloop()