本文共 1979 字,大约阅读时间需要 6 分钟。
Python3.x:遍历select下拉框获取value值
在Web自动化测试中,select下拉框是常见的UI元素,了解如何正确获取其值对于测试开发至关重要。本文将详细介绍如何通过Selenium和BeautifulSoup库遍历select选项,获取value和text属性。
选择方法
select下拉框提供了三种选择方法:
select_by_index(index)select_by_value(value)select_by_visible_text(text)取消选择方法
select提供了四种方法取消选择:
deselect_by_index(index)deselect_by_value(value)deselect_by_visible_text(text)deselect_all()获取选项信息的属性方法
select提供了三个属性方法给我们必要的信息:
optionsall_selected_optionsfirst_selected_option示例一:Selenium遍历select选项列表
以下是使用Selenium获取select选项的代码示例:
from selenium import webdriverdriver = webdriver.PhantomJS()driver.get("http://**********/center_tjbg.shtml")frame = driver.find_element_by_xpath("//iframe[contains(@src,'http://**********/cms-search/monthview.action?action=china&channelFidStr=e990411f19544e46be84333c25b63de6')]") # 进入iframe页面driver.switch_to.frame(frame)select = driver.find_element_by_id("channelFidStr")options_list = select.find_elements_by_tag_name('option')for option in options_list: print("Value is:%s Text is:%s" % (option.get_attribute("value"), option.text))driver.switch_to.default_content()driver.quit() 示例二:BeautifulSoup遍历select选项列表
以下是使用BeautifulSoup获取select选项的代码示例:
url = "http://******************/monthview.action?action=china"headerDict = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.31 Safari/537.36'}data = { 'riqi': '2017年12月', 'channelFidStr': 'e990411f19544e46be84333c25b63de6', 'channelIdStr': '08ce523457dd47d2aad6b41246964535'}res = requests.post(url, data=data, headers=headerDict)soup = BeautifulSoup(res.content, "html.parser")option_list = soup.find(id='channelFidStr').find_all('option')for option in option_list: print("value:%s text:%s" % (option['value'], option.text)) 通过以上方法,我们可以方便地获取select下拉框的value和text属性信息。无论是Selenium还是BeautifulSoup,核心逻辑都是通过获取元素的属性或文本内容来实现的。希望以上内容能为您提供帮助!
转载地址:http://eylfk.baihongyu.com/