web-操作方法二次封装
作者:互联网
关于web页面的相关操作,我们可以进行二次封装,这样用到的时候直接调用即可,虽然封装过程麻烦一点,但多次用起来时会方便很多
新建browser.py代码如下:
from selenium.webdriver import Chrome
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as when
from selenium.webdriver.common.by import By
class Page:
host = 'http://baidu.com'
# driver: Chrome的作用是使用driver.时会提示相关的方法
def __init__(self, driver: Chrome):
self.driver = driver
def goto(self, url):
# 去哪个url地址
if url.find('http://') != -1:
return self.driver.get(url)
return self.driver.get(self.host + url)
def fill(self, locator, words):
# 输入框内输入内容
el = browser.find_element(*locator)
el.send_keys(words)
def click(self, locator):
# 点击
wait = WebDriverWait(browser, timeout=5)
condition = when.element_to_be_clickable(locator)
lemon_link = wait.until(condition)
lemon_link.click()
if __name__ == '__main__':
with Chrome() as browser:
page = Page(browser)
page.goto('/')
page.fill((By.ID, 'kw'), '柠檬班')
page.click((By.ID, 'su'))
page.click((By.LINK_TEXT, 'lemon.ke.qq.com/'))
这样以后测试时,线上线下环境经常改变时,或者直接写url后半部分即可,如:/login,直接调用就可以了
然后就可以调用使用二次封装的代码了
from selenium import webdriver
from selenium.webdriver.common.by import By
from browser import Page
class TestDeom:
def test_01(self):
with webdriver.Chrome() as browser:
page = Page(browser)
page.goto('/')
page.fill((By.ID, 'kw'), '柠檬班')
page.click((By.ID, 'su'))
page.click((By.LINK_TEXT, 'lemon.ke.qq.com/'))
运行结果:
标签:web,封装,webdriver,操作方法,self,driver,import,page,browser 来源: https://blog.csdn.net/weixin_40611700/article/details/121519852