Selenium下拉框的选择

Demo:百度首页 → 设置 → 搜索设置,设置页数

先定位到有下拉框的元素,再使用Select(webelement)的方法:

    .select_by_index()

    .select_by_visible_text()

    .select_by_value()

代码如下:

from timeimport sleep

from seleniumimport webdriver

from selenium.webdriver.support.selectimport Select


driver = webdriver.Chrome()

driver.implicitly_wait(10)

driver.get("https://www.baidu.com")


# 将鼠标悬停至"设置"链接

sleep(1)

webdriver.ActionChains(driver).move_to_element(driver.find_element_by_link_text("设置")).perform()


# 找到并点击"搜索设置"

sleep(1)

driver.find_element_by_link_text("搜索设置").click()


# 定位到下拉框

sleep(1)

select = driver.find_element_by_xpath('//*[@id="nr"]')


#  使用select_by_index方式赋值

Select(select).select_by_index(2)


# 使用select_by_value方式赋值

sleep(1)# 为了看到效果

Select(select).select_by_value("20")


# 使用select_by_visible_text方式赋值

sleep(1)# 为了看到效果

Select(select).select_by_visible_text("每页显示50条")

你可能感兴趣的:(Selenium下拉框的选择)