如何使用Python中的Selenium在下拉列表中选择选项(Jupyter笔记本)

2024-10-02 18:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在(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)

Tags: sendid列表searchbydrivercodeelement
1条回答
网友
1楼 · 发布于 2024-10-02 18:21:39

页面不使用标准的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()

相关问题 更多 >