下拉框处理
一、脚本准备
在项目下新建html文件,命名为drop_down.html。复制粘贴以下内容并保存。
1 <html> 2 <body> 3 <select id="ShippingMethod" onchange="updateShipping(options[selectedIndex]);" 4 name="ShippingMethod"> 5 <option value="12.51">UPS Next Day Air ==> $12.51</option> 6 <option value="11.61">UPS Next Day Air Saver ==> $11.61</option> 7 <option value="10.69">UPS 3 Day Select ==> $10.69</option> 8 <option value="9.03">UPS 2nd Day Air ==> $9.03</option> 9 <option value="8.34">UPS Ground ==> $8.34</option> 10 <option value="9.25">USPS Priority Mail Insured ==> $9.25</option> 11 <option value="7.45">USPS Priority Mail ==> $7.45</option> 12 <option value="3.20" selected="">USPS First Class ==> $3.20</option> 13 </select> 14 </body> 15 </html>
用浏览器打开,效果如下
二、python代码实现
需求:通过脚本选择下拉列表里的$10.69
1 #coding=utf-8 2 from selenium import webdriver 3 import time 4 import os 5 6 driver = webdriver.Firefox() 7 file_path = 'file:///'+os.path.abspath('select.html') 8 driver.get(file_path) 9 time.sleep(2) 10 11 #先定位到下拉框 12 m = driver.find_element_by_id('ShippingMethod') 13 time.sleep(2) 14 #再点击下拉框下的选项 15 m.find_element_by_xpath("//option[@value='10.69']").click() 16 time.sleep(2) 17 18 19 driver.quit()
三、总结
1)找到下拉选择框的元素:
select = driver.find_element_by_id('xxx')
2) 选择对应的选择项并操作:
select.find_element_by_xpath("yyy").click()