Selenium drop-down box operation

Transfer from: https://www.cnblogs.com/youngleesin/p/10460004.html
1. The html source code of the exercise:
copy and paste to the desktop, save it as xx.html, open

<!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>

2. There are three main types of select methods

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 选项 ;

3. Use the above three methods to do a simple exercise

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()

4. Do an exercise for select_by_index with the while loop

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()

Guess you like

Origin blog.csdn.net/zhaoweiya/article/details/107833017