Loading

selenium.下拉框操作(select_by)

练习的html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>下拉框练习</title>
</head>
<body>
<select name="辛弃疾" id="">
    <option value="01">破阵子·为陈同甫赋壮词以寄之</option>
    <option value="02">醉里挑灯看剑,梦回吹角连营。</option>
    <option value="03">八百里分麾下炙,五十弦翻塞外声。沙场秋点兵。</option>
    <option value="04">马作的卢飞快,弓如霹雳弦惊。</option>
    <option value="05">了却君王天下事,赢得生前身后名。</option>
    <option value="06">可怜白发生!</option>
</select>
</body>
</html>

select方法主要有三类

select_by_index(self, index)       #以index属性值来查找匹配的元素并选择;
select_by_value(self, value)        #以value属性值来查找该option并选择;
select_by_visible_text(self, text)  #以text文本值来查找匹配的元素并选择;
first_selected_option(self)         #选择第一个option 选项 ;

使用以上三类方法做个简单的练习

from selenium.webdriver.support.select import Select
from selenium import webdriver
from time import sleep

driver = webdriver.Chrome()
driver.get("file:///C:/Users/ccl/PycharmProjects/untitled2/ccl/selenium_test/select_test.html")
opt = driver.find_element_by_name('辛弃疾')
Select(opt).select_by_visible_text('醉里挑灯看剑,梦回吹角连营。!')
sleep(1)
Select(opt).select_by_index(1)
sleep(1)
Select(opt).select_by_value('03')

driver.quit()

针对 select_by_index 配合while循环做个练习,效果如GIF

from selenium.webdriver.support.select import Select
from selenium import webdriver
from time import sleep

driver = webdriver.Chrome()
driver.get("file:///C:/Users/ccl/PycharmProjects/untitled2/ccl/selenium_test/select_test.html")
opt = driver.find_element_by_name('辛弃疾')
len_op = len(driver.find_elements_by_tag_name("option"))
x = 0

while len_op > x:
    x += 1
    if x == len_op:
        break
    Select(opt).select_by_index(x)
    sleep(1)

sleep(2)
driver.quit()

 

posted @ 2019-04-11 21:26  yonugleesin  阅读(12826)  评论(0编辑  收藏  举报