首页 > 其他分享 >【web自动化】selenium根据浏览器版本下载对应的chromedriver

【web自动化】selenium根据浏览器版本下载对应的chromedriver

时间:2022-08-19 20:55:16浏览次数:65  
标签:web get url selenium self driver chromedriver path browser

1、使用国内的镜像地址

https://registry.npmmirror.com/binary.html?path=chromedriver/

 

2、通过simulation模拟用户点击来下载(只贴出部分方法)

#!/usr/bin/env python  
# -*- coding:utf-8 -*-  
import os
import platform
import signal
import time
import allure
import requests

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


DRIVER_DOWNLOAD_URL = "https://registry.npmmirror.com/binary.html?path=chromedriver/"


class BaseAction(object):
    def __init__(self, mode=0):
        """
        :param mode: 0: 表示无头模式
        """
        self.mode = mode

        self.options = webdriver.ChromeOptions()

        self.serv = Service(executable_path=r"{}".format(self.get_driver_path_by_sys()))
        self.serv.start()
        self.options.add_argument('--headless')
        self.options.add_argument('--disable-gpu')
        if self.sys_type == 'Windows':
            self.browser = webdriver.Chrome(service=self.serv, options=self.options)
        else:
            self.browser = webdriver.Chrome(executable_path=self.get_driver_path_by_sys(), options=self.options)

        self.browser_version = self.get_browser_ver()

    def get_driver_path_by_sys(self):
        self.sys_type = platform.system()
        if self.sys_type == "Windows":
            debug_logger.info("[web] system type: Windows")
            return os.path.join(PROJECT_ROOT_PATH, 'third_party', 'chromedriver', 'chromedriver_win32',
                                'chromedriver.exe')
        elif self.sys_type == "Linux":
            debug_logger.info("[web] system type: Linux")
            return os.path.join(PROJECT_ROOT_PATH, 'third_party', 'chromedriver', 'chromedriver_linux64',
                                'chromedriver')
        else:
            raise Exception("[web]system not support!")

    def get_browser_ver(self):
        self.open_url("http://www.baidu.com/")
        time.sleep(1)
        logger.info("[web]浏览器version:{}".format(self.browser.capabilities.get("browserVersion")))
        return self.browser.capabilities.get("browserVersion")

    def open_url(self, url):
        self.browser.get(url)
        time.sleep(2)
        self.wait = WebDriverWait(self.browser, 20)
        self.browser.maximize_window()def close(self):
        time.sleep(2)
        self.browser.close()
        self.browser.quit()
        self.serv.stop()

    def get_driver_uri(self):
        # 获取webdriver下载列表
        self.open_url(DRIVER_DOWNLOAD_URL)
        # 下载并更新当前webdriver列表
        ele = self.browser.find_elements(By.XPATH, '/html/body/table/tbody/tr/td/a')

        like_version_list = []
        for e in ele:
            if e.text.startswith(self.browser_version.rsplit(".", 1)[0]):
                like_version_list.append(e.text)
        logger.info(f'[web] like_version_list: {like_version_list}')
        # 获取最新版本
        logger.info(f'[web] version_uri: {max(like_version_list)}')
        version_uri = max(like_version_list)
        return version_uri

    def get_system_download_url(self):
        version_uri = self.get_driver_uri()
        self.open_url(DRIVER_DOWNLOAD_URL + version_uri)
        ele = self.browser.find_elements(By.XPATH, '/html/body/table/tbody/tr/td/a')
        url_list = [e.get_attribute('href') for e in ele]
        logger.info(f'[web] url_list: {url_list}')

        if platform.system() == "Windows":
            download_url = [d_url for d_url in url_list if "win" in d_url][0]
        elif platform.system() == "Linux":
            download_url = [d_url for d_url in url_list if "linux" in d_url][0]
        else:
            download_url = None
        logger.info(f'[web] download_url: {download_url}')
        return download_url

    def download_driver_to_local(self):
        download_url = self.get_system_download_url()
        rsp = requests.get(download_url)
        # 删除本地driver文件
        driver_path = self.get_driver_path_by_sys()
        # 关闭占用
        self.close()
        driver_dir = os.path.dirname(driver_path)
        logger.info(f'[web] dir content: {os.listdir(driver_dir)}')
        p_pid = get_pid("chromedriver.exe")
        if p_pid:
            os.kill(p_pid, signal.SIGINT)
        os.unlink(driver_path)
        # 写入下载的文件
        file_name = download_url.rsplit("/", 1)[-1]
        file_dir = os.path.join(driver_dir, file_name)
        with open(file_dir, mode='wb') as f:
            f.write(rsp.content)
        logger.info(f'[web] dir content: {os.listdir(driver_dir)}')
        # 解压文件到当前目录
        unzip_file(file_dir, driver_dir)


if __name__ == '__main__':
    action = BaseAction(mode=0)
    action.download_driver_to_local()

 

标签:web,get,url,selenium,self,driver,chromedriver,path,browser
From: https://www.cnblogs.com/fireblackman/p/16603250.html

相关文章

  • 2022-08-19 田龙跃 JAVAWEB项目(小论坛)
    JAVA小项目E-R图个人理解:E-R图中每个实体到我们对java中就是一个domin类,字段就是属性流程图注册流程图登录流程图JSTL标签jstl表达式:表达式的用法也是见名知义(和......
  • SpringWebflux框架里导出excel文档
    本demo里使用springboot2.7.0版本。@GetMapping("/download/excel/file")publicMono<Void>downloadExcelFile(ServerHttpResponseresponse,WebSessionwebSessi......
  • rancher添加用户报错x509: certificate has expired Internal error occurred: failed
    错误信息:Internalerroroccurred:failedcallingwebhook"rancherauth.cattle.io":Posthttps://rancher-webhook.cattle-system.svc:443/v1/webhook/validation?tim......
  • Sys.WebForms.PageRequestManagerServerErrorException
    在ScriptManager内添加EnablePartialRendering="false"显示详细的错误信息。如下:<asp:ScriptManagerID="ScriptManager1"runat="server"EnablePartialRendering=......
  • websocket的简单使用
    程序git:https://gitee.com/juncaoit/websocketpro 1.引入pom<dependency><groupId>org.springframework.boot</groupId><arti......
  • 文件夹上传组件webupload插件
    ​文件夹数据库处理逻辑public class DbFolder{    JSONObjectroot;       public DbFolder()    {        this.root= new JSONOb......
  • webrtc 合流
    <template><!--大窗口--><divclass="liveVideos"><videoid="camaraVideo"width="100%"height="100%"ref="videoing"c......
  • 大文件上传组件webupload插件
    ​需求:项目要支持大文件上传功能,经过讨论,初步将文件上传大小控制在500M内,因此自己需要在项目中进行文件上传部分的调整和配置,自己将大小都以501M来进行限制。 第一步:......
  • 学习javaweb第1天(数据库连接池)
    10.9、数据库连接池池化技术:准备一些预先的资源,过来就连接预先准备好的数据库连接池实现:标准接口:DataSourse官方(sun)提供的数据库连接池标准接口,由第三方组织实现此接......
  • webrtc-streamer实现简单rtsp视频监控
    环境需求:1.linux服务器2.nginx或其他代理服务 内网项目使用海康摄像机完成简单的视频监控,虽然海康提供了webcomments插件和SDK二次开发工具,但webcomments插件以及无插......