Python自动化操作selenium简便库

Python自动化操作selenium简便库

浮梦 85 2024-01-13

如果想操作固定的chrome去github上下个软件,叫my-chorme,即可打包一个免安装版本的chorme

点击链接,即可跳转到github下载页,如果没有小火箭去github,请留言邮箱,我会发送过去安装包
my-chrome下载地址

自己写的便捷操作selenium的库

import time
import random
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
class seleniumClass():
    def __init__(self, is_Vis=True, binary_location=None, executable_path=None, waitTime=10):
        self.option = webdriver.ChromeOptions()
        self.option.add_argument(
        '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36')
        if is_Vis == False:
            # 指定浏览器在无头模式下运行,即在没有可见窗口的情况下运行,可用于在后台执行测试或爬虫任务。
            self.option.add_argument("--headless")
            # 禁用沙箱模式,可以避免一些权限相关的问题。
            self.option.add_argument('--no-sandbox')
            # 禁用 GPU 加速,可以减少资源消耗。
            self.option.add_argument('--disable-gpu')
            # 禁用/dev/shm的使用,可以减少内存消耗。
            self.option.add_argument('--disable-dev-shm-usage')
        # 排除启用自动化的选项,以避免被检测为自动化程序。
        self.option.add_experimental_option('excludeSwitches', ['enable-automation'])
        # 禁用自动化扩展,以避免被检测为自动化程序。
        self.option.add_experimental_option('useAutomationExtension', False)
        # 禁用所有 Blink 引擎的特性。
        self.option.add_argument('--disable-blink-features')
        # 禁用自动化控制的 Blink 引擎特性。
        self.option.add_argument('--disable-blink-features=AutomationControlled')
        # 如果定义了Chrome地址,那么需要指定路径
        if binary_location != None:
            self.option.binary_location = binary_location
        # 如果定义了chromedriver地址,那么需要指定路径
        if executable_path != None:
            self.driver = webdriver.Chrome(executable_path=executable_path,chrome_options=self.option)
        else:
            self.driver = webdriver.Chrome(chrome_options=self.option)
        self.driver.implicitly_wait(waitTime)
    # 打开Url
    def get_url(self, url):
        self.driver.get(url)
        return self
    # 选取ID元素
    def find_element_by_id(self, id):
        return self.driver.find_element(By.ID, id)
    # 选取Class元素
    def find_element_by_class_name(self, class_name):
        return self.driver.find_element(By.CLASS_NAME, class_name)
    # 使用xpath选取元素
    def find_element_by_xpath(self, xpath):
        return self.driver.find_element(By.XPATH, xpath)
    # 拖动,第一个是元素选择,第二个是拖动距离
    def clickHold(self, slider_element, distrack):
        action = ActionChains(self.driver)

        # 模拟点击并稍作停留
        action.click_and_hold(slider_element)
        time.sleep(random.uniform(0.1, 0.3))  # 随机停留0.1到0.3秒

        # 开始拖动滑块
        initial_location = slider_element.location_once_scrolled_into_view
        total_move = distrack + random.uniform(-5, 5)  # 添加一定的随机偏移量
        action.move_by_offset(total_move, 0)

        # 在接近目标位置时加入微调动作
        near_target_threshold = 20  # 设置一个阈值,在这个范围内进行微调
        if abs(total_move) < near_target_threshold:
            micro_adjust = random.uniform(-3, 3)
            action.move_by_offset(micro_adjust, 0)

        # 松开鼠标按键,完成拖动动作
        action.release()

        # 执行这一系列的动作
        action.perform()
    # 获取字符串cookies
    def get_string_cookies(self):
        arr = self.driver.get_cookies()
        cookieArr = []
        for item in arr:
            cookieArr.append(item['name']+'='+item['value'])
        return ";".join(cookieArr)
    # 设置cookies
    def add_cookies(self, cookies):
        cookieArr = cookies.split(";")
        addCookies = []
        for item in cookieArr:
            self.driver.add_cookie({'name':item.split("=")[0].strip(),'value':item.split("=")[1].strip()})
        return True
    def get_resources_url(self, desc):
        return self.driver.execute_script("return window.performance.getEntriesByType('resource').filter(entry => entry.initiatorType === 'xmlhttprequest' && entry.name.indexOf('"+str(desc)+"') > -1);")[-1]
    # 关闭浏览器
    def close_window(self):
        self.driver.close()