1 """处理下拉框""" 2 3 from selenium import webdriver 4 from selenium.webdriver.common.by import By 5 from selenium.webdriver.support.ui import WebDriverWait 6 from selenium.webdriver.support import expected_conditions as ES 7 from selenium.webdriver.common.action_chains import ActionChains 8 from selenium.webdriver.support.select import Select 9 import time 10 11 12 def elementFind(driver, way, str): 13 """ 14 封装具有等待时间加判断的定位方法 15 :param driver: 16 :param way: 定位方式 17 :param str: 要定位的元素 18 :return: 19 """ 20 try: 21 element = WebDriverWait(driver, 5, 0.5).until(ES.presence_of_element_located((way, str))) 22 return element 23 except: 24 return False 25 26 27 driver = webdriver.Chrome() 28 driver.get("http://www.baidu.com") 29 30 el = elementFind(driver, By.LINK_TEXT, '设置') 31 ActionChains(driver).move_to_element(el).perform() 32 33 time.sleep(1) 34 driver.find_element(By.CSS_SELECTOR, '.setpref').click() 35 36 """ 37 1 select_by_index # 通过索引定位 38 2 select_by_value # 通过value值定位 39 3 select_by_visible_text # 通过文本值定位 40 """ 41 time.sleep(1) 42 s = driver.find_element_by_css_selector("#nr") 43 Select(s).select_by_value('50') 44 45 # 二次定位方式 46 time.sleep(1) 47 driver.find_element_by_id("nr").find_element_by_xpath("//option[@value='20']").click() 48 49 time.sleep(3) 50 driver.quit()