如何在Selenium中选择列表?

2024-09-28 03:22:42 发布

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

我试图输入一个地址,然后他们向我推荐了一些地址,我不知道如何选择他们给我的第一个选项

如果您想尝试,请在该链接的第二步:https://www.sneakql.com/en-GB/launch/culturekings/womens-air-jordan-1-high-og-court-purple-au/register

adresse = chrome.find_element_by_id('address-autocomplete')
            adresse.send_keys(row['Adresse']) #Adress from a file
            time.sleep(5)
            country = chrome.find_element_by_xpath('//li[@id="suggestion_0"]').click();

检查元件:

Inspect element


Tags: httpscomidby链接地址www选项
2条回答

您应该单击此字段,然后等待第一个选项变为可单击

我已经编写了一些代码来测试我的解决方案是否有效,并且在所有情况下对我都有效:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


url = 'https://www.sneakql.com/en-GB/launch/culturekings/womens-air-jordan-1-high-og-court-purple-au/register'
driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver')
driver.get(url)
wait = WebDriverWait(driver, 15)
wait.until(EC.element_to_be_clickable((By.XPATH, "//span[contains(text(),'AGREE')]"))).click()  # ACCEPT COOKIES

#  Making inputs of the first page
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#firstName"))).send_keys("test")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#lastName"))).send_keys("Last name")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#preferredName"))).send_keys("Mr. President")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#email"))).send_keys("mr.president@gmail.com")
driver.find_element_by_css_selector("#password").send_keys("11111111")
driver.find_element_by_css_selector("#phone").send_keys("222334413")
driver.find_element_by_css_selector("#birthdate").send_keys("2000-06-11")
wait.until(EC.element_to_be_clickable((By.XPATH, "//span[contains(text(),'Next')]"))).click()

# Second page and answer to your main question
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#address-autocomplete"))).send_keys("street")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#suggestion_0"))).click()

请注意,并非所有显式等待都是必需的,我使用了css选择器,因为我不确定所有元素ID是否正确

我的输出: enter image description here

尝试用以下命令单击第一个选项:

driver.find_element_by_xpath('//li[@id="suggestion_0"]')

UPD
试图单击的图元不在视图中。您必须执行以下操作:

from selenium.webdriver.common.action_chains import ActionChains

suggestion_0 = driver.find_element_by_xpath('//li[@id="suggestion_0"]')

actions = ActionChains(driver)
actions.move_to_element(suggestion_0).perform()
suggestion_0.click()

相关问题 更多 >

    热门问题