python+selenium select下拉选择框定位处理方法

yipeiwu_com6年前Python基础

一、前言

总结一下python+selenium select下拉选择框定位处理的两种方式,以备后续使用时查询;

二、直接定位(XPath)

使用Firebug找到需要定位到的元素,直接右键复制XPath,使用find_element_by_xpath定位;

driver = webdriver.Firefox()
driver.get("https://www.baidu.com/")
driver.find_element_by_xpath().click()

三、间接定位(Select模块)

页面HTML源码如下所示:

<select id="nr" name="NR">
<option value="10" selected="">每页显示10条</option>
<option value="20">每页显示20条</option>
<option value="50">每页显示50条</option>
</select>

python+selenium 代码如下:

# coding:utf-8
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
import time
 
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
driver.implicitly_wait(20)
 
mouse = driver.find_element_by_link_text("设置")
ActionChains(driver).move_to_element(mouse).perform()
driver.find_element_by_link_text("搜索设置").click()
time.sleep(2)
# 实例化select
s = Select(driver.find_element_by_id("nr"))
# 定位选项
s.select_by_value("20") # 选择value="20"的项:通过value属性
time.sleep(2) #为了明显的看出变化
s.select_by_index(0) # 选择第一项选项:通过选项的顺序选择,第一个为 0
time.sleep(2) #为了明显的看出变化
s.select_by_visible_text("每页显示50条") # 选择text="每页显示50条"的值,即在下拉时我们可以看到的文本

四、总结

Select提供了三种选择方法:

select_by_index(index) ——通过选项的顺序,第一个为 0

select_by_value(value) ——通过value属性

select_by_visible_text(text) ——通过选项可见文本

Select提供了四种方法取消选择:

deselect_by_index(index) 
deselect_by_value(value) 
deselect_by_visible_text(text) 
deselect_all()

Select提供了三个属性方法提供信息:

options ——提供所有的选项的列表,其中都是选项的WebElement元素

all_selected_options ——提供所有被选中的选项的列表,其中也均为选项的WebElement元素

first_selected_option ——提供第一个被选中的选项,也是下拉框的默认值

通过Select提供的方法和属性,我们可以对标准select下拉框进行任何操作,但是对于非select标签的伪下拉框,需要使用XPath定位;

以上这篇python+selenium select下拉选择框定位处理方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现从网络下载文件并获得文件大小及类型的方法

本文实例讲述了python实现从网络下载文件并获得文件大小及类型的方法。分享给大家供大家参考。具体实现方法如下: import urllib2 from settings impor...

Python 列表list使用介绍

一组有序项目的集合 可变的数据类型【可进行增删改查】 列表中可以包含任何数据类型,也可包含另一个列表【可任意组合嵌套】 列表是以方括号“[]”包围的数据集合,不同成员以“,”分隔 列表...

python使用json序列化datetime类型实例解析

使用python的json模块序列化时间或者其他不支持的类型时会抛异常,例如下面的代码: # -*- coding: cp936 -*- from datetime import d...

Python中的Function定义方法第1/2页

下面就先定义一个函数: 复制代码 代码如下:def foo(): print('function') foo() 在上述代码中,定义了一个名为foo的函数,这个函数没有参数。最后一行代码...

Windows下实现Python2和Python3两个版共存的方法

一直用的是python2,从python 2.3到python 2.7.6, 出于想了解python3的新特性,又安装了python3.3.3. 用了才发现蛮方便的。python的各个版...