要使用Selenium操作下拉框,可以参考以下步骤:
# 导入所需的模块
from selenium import webdriver
from selenium.webdriver.support.ui import Select
# 创建chrome浏览器驱动
driver = webdriver.Chrome()
# 打开网页
driver.get('http://example.com')
# 定位到下拉框元素
select_element = driver.find_element_by_xpath('//select[@id="select-id"]')
# 创建Select对象
select = Select(select_element)
# 按照文本选择选项
select.select_by_visible_text('选项文本')
# 按照value选择选项
select.select_by_value('选项值')
# 按照索引选择选项
select.select_by_index(0)
# 关闭浏览器驱动
driver.quit()
代码实现:
drop_down.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<select id="shippingMethod" 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>Koption 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>
main.py
from selenium import webdriver
import os
from time import sleep
def testdropdown():
options=webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors') # 忽略证书告警
options.add_argument('--no-sandbox') # root 权限
options.add_argument('--disable-dev-shm-usage') # 关闭开发者模式
# options.add_argument('--headless') # 无图像化界面:"
# options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片
options.add_argument('--disable-gpu') # 关闭GPU
options.add_experimental_option("excludeSwitches", ["enable-logging"]) # 忽视蓝牙适配器
driver = webdriver.Chrome(chrome_options=options)
file_path = 'file:///'+os.path.abspath('./1/html/drop_down.html')
driver.get(file_path)
sleep(3)
select = driver.find_element_by_name("shippingMethod")
select.find_element_by_xpath("//option[@value='7.45']").click()
sleep(3)
driver.quit()
if __name__=="__main__":
testdropdown()