其他分享
首页 > 其他分享> > selenium-浏览器操作封装

selenium-浏览器操作封装

作者:互联网

from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from loguru import logger
from collections import namedtuple

Locator = namedtuple('Locator', ('type', 'value'))

class Browser:

    def __init__(self, driver=None, config=None):
        self.driver = driver or Chrome()
        self.config = config or {}
        self.waiter = WebDriverWait(self.driver, timeout=self.config.get('timeout', 20))

    # 页面级操作

    def get(self, url):
        logger.info(f'打开网页 => {url}')
        self.driver.maximize_window()
        self.driver.set_page_load_timeout(self.config.get('page_max_load_time', 20))
        self.driver.get(url)

    def f5(self):
        self.driver.refresh()

    def close(self):
        self.driver.close()

    @property
    def html(self):
        return self.driver.page_source

    # js操作
    def js(self, script: str, *args):
        self.driver.execute_script(script, *args)

    # 元素级操作

    def _accord_wait(self, scanner):
        """显示等待"""
        return self.waiter.until(scanner)

    def find_element(self, locator: Locator):
        return self._accord_wait(ec.presence_of_element_located(locator))

    def find_elements(self, locator):
        return self._accord_wait(ec.presence_of_all_elements_located(locator))

    def input(self, locator: Locator, text):
        self.find_element(locator).send_keys(text)

    def click(self, locator: Locator):
        self.find_element(locator).click()

    def text(self, locator: Locator):
        return self.find_element(locator).text


def test():
    options = ChromeOptions()
    options.add_argument('--headless')  # 无界面
    options.add_argument('--no-sandbox')  # root权限
    options.add_argument('--disable-dev-shm-usage') # 禁止共享内存
    driver = Chrome(options=options)
    browser = Browser(driver=driver)
    browser.get('http://www.baidu.com')


标签:浏览器,Locator,selenium,self,driver,locator,import,封装,def
来源: https://www.cnblogs.com/bonus_scene/p/15212667.html