python中的Selenium:从没有唯一标识符的span或ul下的下拉列表中选择一个预定义的单词



我一直在试图弄清楚这一点,并到处搜索,但找不到答案。我正在尝试使用Python中的Selenium来填写一个表单。我已经完成了其中的几个部分,但我陷入了困境。我想我可能有两个问题。

1.(在Selenium点击下拉菜单后,我不知道下一个元素应该是什么。

2.(我不知道如何通过预定义的名称从下拉列表中选择一个值。在这种情况下;马里科帕";用于县下拉列表。

在我理想的世界里,我只需要通过用户输入或通过我生成的预定义列表将县名传递到代码中。它会从下拉列表中选择该县,然后允许我让Selenium单击搜索按钮。

到目前为止我所拥有的:


import numpy as np
import pandas as pd
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
PATH = 'C:Program FilesGoogleChromechromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get("https://www.arizonapublicnotices.com/")
time.sleep(2)
burg_but = driver.find_element_by_xpath("//*[@id='__next']/div/div/div[2]/div/div[1]/div[1]/button")
burg_but.click() # Click the dropdown menu on the top left

sdate_cookie = driver.find_element_by_xpath("//*[@id='__next']/div/div/div[3]/div/div/div/div/section/div/div/div/div[1]/div[2]/div[1]/div/div/div/div/div/div[1]/div/input")
sdate_cookie.click() # Update start date
sdate_cookie.send_keys(Keys.CONTROL, "a") # Select all pre-existing text/input value
sdate_cookie.send_keys(Keys.BACKSPACE)    # Remove that text
sdate_cookie.send_keys('05/01/2021')

edate_cookie = driver.find_element_by_xpath("//*[@id='__next']/div/div/div[3]/div/div/div/div/section/div/div/div/div[1]/div[2]/div[2]/div/div/div/div/div/div[1]/div/input")
edate_cookie.click() # Update end date
edate_cookie.send_keys(Keys.CONTROL, "a") # Select all pre-existing text/input value
edate_cookie.send_keys(Keys.BACKSPACE)    # Remove that text
edate_cookie.send_keys('05/31/2021')
county_cookie = driver.find_element_by_xpath("//*[@id='headlessui-listbox-button-5']").click() # Select dropdown for county
# NEED CODE HERE -> SELECT "Maricopa" (or other user defined county from dropdown)

search_but = driver.find_element_by_xpath("//*[@id='__next']/div/div/div[3]/div/div/div/div/section/div/div/div/div[5]/span[2]/button")
search_but.click() # Click search button
search_cookie = driver.find_element_by_xpath("//*[@id='__next']/div/div/div[2]/div/div[1]/div[2]/div/div[2]/input")
search_cookie.click()
search_cookie.send_keys('creditors') # Refine search to specific word "creditors"

我犯了很多错误,不知道该发哪一个。其中大多数都与无法通过XPath选择元素或无法与我选择的元素交互有关。

希望得到任何帮助。这是我发布的第一个问题。我欢迎任何关于如何更好地发布我的问题的反馈。

David

设法以这种方式选择国家:

from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
country = 'Maricopa' <= PASS IN COUNTRY NAME HERE
country_xpath=f"//span[contains(.,'{country}')]"
country_box = driver.find_elements_by_xpath('//*[@id="headlessui-listbox-options-9"]')
for i in country_box:
actions.move_to_element(i).perform()
driver.find_element_by_xpath(country_xpath).click()

最新更新