欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python对Selenium调用浏览器进行封装包括启用无头浏览器,及对应的浏览器配置文件

程序员文章站 2022-05-14 12:53:53
""" 获取浏览器 打开本地浏览器 打开远程浏览器 关闭浏览器 打开网址 最大化 最小化 标题 url 刷新 Python对Selenium封装浏览器调用 browser.py文件 """ from selenium import webdriver from Common.tools.rw_ini ......

"""
获取浏览器
打开本地浏览器
打开远程浏览器
关闭浏览器
打开网址
最大化
最小化
标题
url
刷新

python对selenium封装浏览器调用

------browser.py文件
"""

from selenium import webdriver

from common.tools.rw_ini import read_config
from .base import base


class browser(base):
    def get_web_driver(self) -> webdriver.remote:
        """获取浏览器实例

        :return: 浏览器实例
        """
        rc = read_config("browser.ini")
        local_browser = rc.getboolean("local", "local_browser", fallback=true)
        wait_time = rc.getint("local", "wait_time", fallback=10)

        browser_name = rc.get("browser", "name", fallback="chrome")
        window_width = rc.get("browser", "window_width", fallback=none)
        window_height = rc.get("browser", "window_height", fallback=none)

        command_executor = rc.get("grid", "command_executor", fallback="http://127.0.0.1:4444/wd/hub")
        headless = rc.getboolean("grid", "headless", fallback=false)
        proxy = rc.get("grid", "proxy", fallback=none)

        if local_browser:
            # 打开本地浏览器
            driver = self._get_local_web_driver(browser_name)
        else:
            # 打开远程浏览器
            driver = self._get_remote_web_driver(browser_name, command_executor, headless, proxy)
        self.logger.info(f"打开浏览器:{driver.name}")

        self.logger.info(f"设置隐式等待:{wait_time}s")
        driver.implicitly_wait(wait_time)

        if window_width is none or window_width == "" or window_height is none or window_height == "":
            self.logger.info("最大化浏览器")
            driver.maximize_window()
        else:
            driver.set_window_size(window_width, window_height)
        return driver

    def _get_local_web_driver(self, browser_name: str) -> webdriver.remote:
        """获取本地浏览器实例

        :param browser_name: 浏览器类型
        :return: 浏览器实例
        """
        if browser_name.upper() == "chrome":
            driver = webdriver.chrome()
        elif browser_name.upper() == "firefox":
            driver = webdriver.firefox()
        elif browser_name.upper() == "ie":
            driver = webdriver.ie()
        else:
            self.logger.error(f"浏览器类型错误:{browser_name}")
            raise valueerror(f"浏览器类型错误:{browser_name}")
        return driver

    def _get_remote_web_driver(self, browser_name, command_executor, headless, proxy) -> webdriver.remote:
        """获取远程浏览器实例

        :param browser_name: 浏览器类型
        :param command_executor: hub 地址
        :param headless: 使用无头浏览器
        :param proxy: 代理
        :return: 浏览器实例
        """
        if browser_name.upper() == "chrome":
            options = webdriver.chromeoptions()
        elif browser_name.upper() == "firefox":
            options = webdriver.firefoxoptions()
        elif browser_name.upper() == "ie":
            options = webdriver.ieoptions()
        else:
            self.logger.error(f"浏览器类型错误:{browser_name}")
            raise valueerror(f"浏览器类型错误:{browser_name}")

        if proxy is not none:
            options.add_argument(f"--proxy-server={proxy}")
        # 无头浏览器
        options.headless = headless

        driver = webdriver.remote(
            command_executor=command_executor,
            options=options
        )
        return driver

    def quit(self):
        """退出浏览器"""
        self.logger.info(f"关闭浏览器:{self.driver.name}")
        self.driver.quit()

    def get(self, url: str, new: bool = false):
        """打开 url

        :param url: 网址
        :param new: 是否新窗口打开
        :return: none
        """
        if new:
            self.logger.info(f"新窗口打开 url:{url}")
            self.driver.execute_script(f"window.open('{url}')")
        else:
            self.logger.info(f"当前窗口打开 url:{url}")
            self.driver.get(url)

    def get_session_id(self):
        """返回当前浏览器 session id"""
        session_id = self.driver.session_id
        self.logger.info(f"当前浏览器 session_id:{session_id}")
        return session_id

    def get_source(self) -> str:
        """获取当前页面html源代码"""
        page_source = self.driver.page_source
        self.logger.info(f"当前页面源代码:\n{page_source}")
        return page_source

    def get_title(self):
        """返回当前页面的标题"""
        title = self.driver.title
        self.logger.info(f"当前页面的标题:{title}")
        return title

    def get_current_url(self):
        """返回当前页面的url"""
        current_url = self.driver.current_url
        self.logger.info(f"当前页面url:{current_url}")
        return current_url

    def reload_page(self):
        """模拟用户重新加载页面"""
        self.logger.info("刷新页面")
        self.driver.refresh()

浏览器配置文件:

------browser.ini文件

[local]
local_browser = false
wait_time = 10

[browser]
name = chrome
;name = firefox
;name = ie
window_width =
window_height =

[grid]
command_executor = http://127.0.0.1:4444/wd/hub
headless = false
proxy =

rw_ini.py读取配置文件请查看下面链接:
https://www.cnblogs.com/cesarezhang/p/10738541.html