【问题标题】:How to select option in dropdown using Selenium in Python (Jupyter Notebook)如何在 Python 中使用 Selenium 在下拉列表中选择选项(Jupyter Notebook)
【发布时间】:2021-09-19 06:00:40
【问题描述】:

我正在尝试在 (https://www.theknot.com/registry/couplesearch) 上选择 2021 年的下拉年份,但无法弄清楚如何使用该下拉菜单。

#This code is working
typetextfirst = driver.find_element_by_id("couples-search-first-name")
typetextfirst.clear()
typetextfirst.send_keys(row["First"])
typetextlast = driver.find_element_by_id("couples-search-last-name")
typetextlast.clear()
typetextlast.send_keys(row["Last"])


typetextyear = driver.find_element_by_id("couples-search-year")
#None of these options work to populate the year
typetextyear.selectByIndex(1)
typetextyear.select_by_index(1)
typetextyear.selectByVisibleText("2021")
typetextyear.select_by_visible_text("2021")

#This code is working
typetextlast.send_keys(Keys.ENTER)

【问题讨论】:

  • 总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是截图,不是链接到外部门户)有问题(不是评论)。还有其他有用的信息。
  • 它不使用标准下拉小部件,而是使用buttonul创建的一些小部件,也许您应该单击它并使用键arrow down移动到选定的年份并发送ENTER .

标签: python selenium driver dropdown


【解决方案1】:

页面不使用标准的dropdown 小部件,但它使用buttonul 来模拟dropdown

此代码适用于我在 Linux Mint 上的 FirefoxChrome

首先我单击button 打开使用ul 创建的dropdown,然后我搜索带有预期文本的li 并单击它。

因为它可能有文字2021 和一些spaces/tabs/enters(浏览器不显示)所以我更喜欢contains 而不是=

from selenium import webdriver
             
url = 'https://www.theknot.com/registry/couplesearch'

driver = webdriver.Firefox()
#driver = webdriver.Chrome()

driver.get(url)

year_dropdown = driver.find_element_by_id("couples-search-year")
year_dropdown.click()

year = year_dropdown.find_element_by_xpath(".//li[contains(text(), '2021')]")
#year = year_dropdown.find_element_by_xpath(".//li[text()='2021']")
year.click()

【讨论】:

    猜你喜欢
    • 2021-05-24
    • 1970-01-01
    • 2021-06-11
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    相关资源
    最近更新 更多