本文主要是介绍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-浏览器操作封装的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!