from selenium.webdriver import Chrome from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as when class Page: host = 'http://www.baidu.com' def __init__(self, driver: Chrome): self.driver = driver def goto(self, url): """去哪个url地址""" # url = http://wefoweowef if url.find('http://') != -1: return self.driver.get(url) return self.driver.get(self.host + url) def fill(self, locator, words): """输入框当中填入""" el = self.driver.find_element( *locator ) el.send_keys(words) def click(self, locator): """点击""" wait = WebDriverWait(self.driver, timeout=5) condition = when.element_to_be_clickable( locator ) element = wait.until(condition) element.click() if __name__ == '__main__': with Chrome(executable_path='chromedriver_95.exe') 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/') )
最后在测试中可以这么调用:
import time from selenium import webdriver from selenium.webdriver import ChromeOptions from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as when from browser import Page class TestDemo: def test_01(self): service = Service(executable_path='chromedriver_95.exe') with webdriver.Chrome(service=service) 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/'))
小技巧:在browser后加Chrome可以在写代码时有联想功能