如何在 Python 中使用 Selenium 在下拉列表中选择 select (Jupyter Notebook)
How to select option in dropdown using Selenium in Python (Jupyter Notebook)
我正在尝试 select 2021 年(https://www.theknot.com/registry/couplesearch)的下拉菜单,但我不知道如何使用下拉菜单。
#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)
页面不使用标准 dropdown
小部件,但它使用 button
和 ul
来模拟 dropdown
.
此代码适用于 Firefox
和 Chrome
Linux Mint。
首先,我单击 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()
我正在尝试 select 2021 年(https://www.theknot.com/registry/couplesearch)的下拉菜单,但我不知道如何使用下拉菜单。
#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)
页面不使用标准 dropdown
小部件,但它使用 button
和 ul
来模拟 dropdown
.
此代码适用于 Firefox
和 Chrome
Linux Mint。
首先,我单击 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()