Selenium---Python3---下拉框选择处理
下拉框一般处理是两次点击,第一次点击弹出下拉框,第二次点击操作元素。
(注释:有些下拉框是鼠标移动上去直接弹出的,我们可以使用方法move_to_element()来处理)
<html> <body> <select id="ShippingMethod" onchange="updateShipping(options[selectedIndex]);" name="ShippingMethod"> <option value="12.51">UPS Next Day Air ==> $12.51</option> <option value="11.61">UPS Next Day Air Saver ==> $11.61</option> <option value="10.69">UPS 3 Day Select ==> $10.69</option> <option value="9.03">UPS 2nd Day Air ==> $9.03</option> <option value="8.34">UPS Ground ==> $8.34</option> <option value="9.25">USPS Priority Mail Insured ==> $9.25</option> <option value="7.45">USPS Priority Mail ==> $7.45</option> <option value="3.20" selected="">USPS First Class ==> $3.20</option> </select> </body> </html>
#coding = utf-8 from selenium import webdriver import os,time #Selenium 下拉框处理 #D:\chromedriver_win32\chromedriver.exe class driver_1(object): #定义一个对象 def __init__(self): self.driver = webdriver.Chrome('D:\chromedriver_win32\chromedriver.exe') def driver_alert(self): file_path = 'file:///' + os.path.abspath('drop_down.html') self.driver.get(file_path) time.sleep(2) #先定位到下拉框 m = self.driver.find_element_by_id('ShippingMethod') #点击下拉框下的选项 m.find_element_by_xpath('//option[@value="10.69"]').click() time.sleep(3) #退出浏览器 self.driver.close() if __name__ == "__main__": a = driver_1() a.driver_alert()