场景:selenium的下拉选项是ul-li模式,选定某个指定的选项。
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC # 显示等待def select_li(self, text, *ul_locator):"""定位ul_li下拉选项中某个指定的下拉选项li:param text: 预期的输入项:param ul_locator: 定位到ul元素:return:"""try:ul_ele = WebDriverWait(self.driver, self.WAIT_TIME, 1).until(EC.visibility_of_element_located((ul_locator)))except Exception as e:self.logger.error("ul元素在{}秒内定位失败: {}".format(self.WAIT_TIME, ul_locator))else:lis = ul_ele.find_elements('tag name', 'li') # 拼接定位元素lifor i in range(1, len(lis) + 1):# 拼接下拉选项的css locator的定位元素li = ul_locator[1] + ">li:nth-child(" + str(i) + ")>span"ele = WebDriverWait(self.driver, self.WAIT_TIME, 1).until(EC.presence_of_element_located((By.CSS_SELECTOR, li)))if text in ele.text: # 判断某个定位元素li的text是否是要选定的选项ele.click() # 点击下拉选项else:self.logger.error("li元素在{}秒内定位失败".format(self.WAIT_TIME))