【问题标题】:Unable to locate element using selenium Python无法使用 selenium Python 定位元素
【发布时间】:2020-11-05 00:42:25
【问题描述】:

我正在尝试使用 Python 中的 Selenium 将信息输入到输入字段中。我无法找到到期日期和 CVV 字段。我知道它们在 iframe 中,但我只能正确输入信用卡号。其他的都是空的。

这是我目前所拥有的:

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.audiobooks.com/signup")
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='braintree-hosted-field-number']")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='number' and @id='credit-card-number']"))).send_keys("1234567890987654")

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='braintree-hosted-field-expirationDate']")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='expirationDate' and @id='expirationDate']"))).send_keys("11/21")

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='braintree-hosted-field-cvv']")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='cvv' and @id='cvv']"))).send_keys("123")

我使用的网址是:https://www.audiobooks.com/signup

【问题讨论】:

    标签: selenium xpath


    【解决方案1】:

    要切换到下一个 iframe,您需要先切换回主 DOM。所以只需在帧切换行之间添加以下代码:

    driver.switch_to.default_content()
    

    你的最终代码:

    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='braintree-hosted-field-number']")))
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='number' and @id='credit-card-number']"))).send_keys("1234567890987654")
    
    driver.switch_to.default_content()
    
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='braintree-hosted-field-expirationDate']")))
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='expirationDate' and @id='expiration']"))).send_keys("11/21")
    
    driver.switch_to.default_content()
    
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='braintree-hosted-field-cvv']")))
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='cvv' and @id='cvv']"))).send_keys("123")
    

    【讨论】:

    • 过期日期和cvv仍然为空
    • @Recidivist ,是的,您的定位器不正确:您需要 @id='expiration' 而不是 @id='expirationDate'。尝试更新代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多