selenium-浏览器操作封装
Posted 花儿向阳开
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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\')
以上是关于selenium-浏览器操作封装的主要内容,如果未能解决你的问题,请参考以下文章
Python_Selenium之basepage 识别元素浏览器操作获取属性鼠标事件键盘事件弹窗切换frame切换句柄封装(持续更新中...)
selenium学习中级篇 -20封装BasePage基础类