selenium 从输入中单击下拉列表值问题

ddrv8njm  于 2022-12-26  发布在  其他
关注(0)|答案(1)|浏览(146)
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait


wait = WebDriverWait

driver = webdriver.Chrome()
driver.get('website')

customerid_form_elements = driver.find_elements(By.CSS_SELECTOR, "input[aria-labelledby='i1']")
for form_element in customerid_form_elements:
    form_element.send_keys("test")

charge_input = input("Charge Amount: ")
form_charge = driver.find_elements(By.CSS_SELECTOR, "input[aria-labelledby='i5']")
for charge in form_charge:
    charge.send_keys(charge_input)

user_input = input("Card & CVV '6969696969696969 666': ")
input_list = user_input.split()

text_field_1 = driver.find_element(By.CSS_SELECTOR, "input[aria-labelledby='i9']")
text_field_2 = driver.find_element(By.CSS_SELECTOR, "input[aria-labelledby='i21']")
text_field_1.send_keys(input_list[0])
text_field_2.send_keys(input_list[1])

last_four_field = driver.find_element(By.CSS_SELECTOR, "input[aria-labelledby='i25']")
card_number = input_list[0]
last_four = card_number[-4:]
last_four_field.send_keys(last_four)

expiration_date = input("Expiration date (MM): ")

dropdown_element = driver.find_element(By.XPATH, "//div[@jsname='LgbsSe']")
dropdown_element.click()

options = driver.find_elements(By.XPATH, "//div[@jsaction and starts-with(@data-value, '[01]')]")

for option in options:
    if option.get_attribute("data-value") == expiration_date:
        option.click()
        break

一切都运行良好,直到它必须点击我从下拉菜单输入的数据值。不能使用选择器,因为它是一个div类。相当混乱。看到图片的jsaction值我试图点击基于我的输入。
HTML pic

m2xkgtsf

m2xkgtsf1#

我已经修改了你的一些代码,请尝试:
对于“Customer ID”字段,定位器只有一个匹配项,因此您需要使用find_elementsfor循环,您可以使用以下代码:

# for Customer ID field
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[aria-labelledby='i1']"))).send_keys("test")

# for 'Expiration Month' field:
expiration_date = input("Expiration date (MM): ")  # you have to enter the value in the format - '01' or '02'... 

dropdown_element = driver.find_element(By.XPATH, "(//div[@jsname='LgbsSe'])[1]")
dropdown_element.click()
time.sleep(2)   # increased the wait time

options = driver.find_elements(By.CSS_SELECTOR, ".OA0qNb.ncFHed.QXL7Te .MocG8c.HZ3kWc.mhLiyf span")

for option in options:
    time.sleep(1)     # added wait time
    if option.text == expiration_date:
        option.click()
        break

# for Expiration Year field
expiration_month = input("Expiration Year (YYYY): ")  # you have to enter the value in the format - "2021" or "2022"...
time.sleep(1)
dropdown_element_2 = driver.find_element(By.XPATH, "(//div[@jsname='LgbsSe'])[2]")
dropdown_element_2.click()
time.sleep(1)

options = driver.find_elements(By.CSS_SELECTOR, ".OA0qNb.ncFHed.QXL7Te .MocG8c.HZ3kWc.mhLiyf span")

for option in options:
    if option.text == expiration_month:
        option.click()
        break

相关问题