1、一般情况下都是先定位元素在选择
from selenium.webdriver import Chrome from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC driver = Chrome() driver.get('http://www.baidu.com') setting_ele_xpath = '//a[@name="tj_settingicon" and @href="http://www.baidu.com/gaoji/preferences.html"]' wait = WebDriverWait(driver, 20) e = wait.until(EC.visibility_of_element_located((By.XPATH, setting_ele_xpath))) driver.find_element_by_xpath(setting_ele_xpath).click() locator = (By.XPATH, "//a[contains(text(), '高级搜索')]") WebDriverWait(driver, 30).until(EC.element_to_be_clickable(locator)).click() # 通常先去定位selector,再去定位option # wait = WebDriverWait(driver, 20) # my_selector = wait.until(EC.element_to_be_clickable((By.NAME, 'ft'))) # my_selector.click() # 在源代码中已经加载出来了,可以直接去点击 wait = WebDriverWait(driver, 20) my_option = wait.until(EC.element_to_be_clickable((By.XPATH, '//option[@value="ppt"]'))) my_option.click()
2、使用selector选择器
from selenium.webdriver import Chrome from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support.select import Select from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC driver = Chrome() driver.get('http://www.baidu.com') def wait_clicl_element(driver, locator): wait = WebDriverWait(driver, 20) return wait.until(EC.element_to_be_clickable(locator)) setting_ele_xpath = '//a[@name="tj_settingicon" and @href="http://www.baidu.com/gaoji/preferences.html"]' wait = WebDriverWait(driver, 20) e = wait.until(EC.visibility_of_element_located((By.XPATH, setting_ele_xpath))) driver.find_element_by_xpath(setting_ele_xpath).click() locator = (By.XPATH, "//a[contains(text(), '高级搜索')]") WebDriverWait(driver, 30).until(EC.element_to_be_clickable(locator)).click() wait = WebDriverWait(driver, 20) my_selector = wait.until(EC.element_to_be_clickable((By.NAME, 'ft'))) my_selector.click() # select选择有3种方法:索引值、value值、文本,点进源码去看 selector_obj = Select(my_selector) selector_obj.select_by_value('pdf') # 取消 selector_obj.deselect_by_value() print(selector_obj.options) print(selector_obj.first_selected_option)