Python3.x:遍历select下拉框获取value值详解编程语言

Python3.x:遍历select下拉框获取value值

Select提供了三种选择方法:

# 通过选项的顺序,第一个为 0  
select_by_index(index) 
# 通过value属性  
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提供了三个属性方法给我们必要的信息:

# 提供所有的选项的列表,其中都是选项的WebElement元素  
options  
# 提供所有被选中的选项的列表,其中也均为选项 
all_selected_options的WebElement元素  
# 提供第一个被选中的选项,也是下拉框的默认值 
first_selected_option 

示例一:代码(selenium遍历select选项列表):

from selenium import webdriver 
 
driver = webdriver.PhantomJS() 
driver.get("http://************/center_tjbg.shtml") 
#通过contains函数,提取匹配特定文本的所有元素 
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标签 
select = driver.find_element_by_id("channelFidStr") 
# 获取select里面的option标签,注意使用find_elements 
options_list=select.find_elements_by_tag_name('option') 
# 遍历option 
for option in options_list: 
    #获取下拉框的value和text 
    print ("Value is:%s  Text is:%s" %(option.get_attribute("value"),option.text)) 
#退出iframe 
driver.switch_to_default_content() 
driver.quit()

 示例二:代码(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'} 
# psot 传递参数 
res = requests.post(url, data=data, headers=headerDict) 
# 获取跳转后的页面源码 
soup = BeautifulSoup(res.content, "html.parser") 
#获取select的选项列表 
option_list = soup.find(id='channelFidStr').find_all('option') 
#遍历select的选项列表 
for option in option_list: 
    print("value:%s text:%s"%(option['value'],option.text))

 

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/16772.html

(0)
上一篇 2021年7月19日 19:37
下一篇 2021年7月19日 19:37

相关推荐

发表回复

登录后才能评论