本篇博文仍以https://www.17sucai.com/pins/demo-show?id=5926,这个网址示例如何进行下拉列表的选项选择。
选择下拉列表的时候,存在两种情况。第一种是有select标签的,这种情况下可以通过from selenium.webdriver.support.ui import Select方式实现,如图片情形。
但也存在没有select标签的下拉列表,这时候就需要我们手动链接到该位置。如图片情形所示,就是a标签,不是select标签,无法通过from selenium.webdriver.support.ui import Select方式实现
下面我们分别来讲第一个情形和第二个情形的操作方法。
- 第一个情形
'''
第一种情形:可以通过 from selenium.webdriver.support.ui import Select
'''
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
driver.get('https://www.17sucai.com/pins/demo-show?id=5926')
# 切换ifrane
driver.switch_to_frame(driver.find_element_by_id('iframe'))
# 找到下拉框
selectTag = Select(driver.find_element_by_name('country-wrap')) # select标签
# 获得选择项
# 1.根据值来选择
selectTag.select_by_value('CA')
# 2.根据索引来选择
# selectTag.select_by_index(3)
- 第二个情形
'''
第二种情形:手动点击
'''
from selenium import webdriver
from selenium.webdriver.support.ui import Select
# 输入选择项
key = int(input('请输入选择内容:'))
driver = webdriver.Chrome()
driver.get('https://www.17sucai.com/pins/demo-show?id=5926')
# 切换ifrane
driver.switch_to_frame(driver.find_element_by_id('iframe'))
# 找到下拉框
selectTag = driver.find_element_by_xpath('//*[@id="dk_container_country-nofake"]').click() # 点击下拉列表位置
# 获得选择项
if key==1:
driver.find_element_by_xpath('//*[@id="dk_container_country-nofake"]/div/ul/li[1]/a').click()
elif key==2:
driver.find_element_by_xpath('//*[@id="dk_container_country-nofake"]/div/ul/li[2]/a').click()