selenium - 无法使用 selenium Python 定位元素

标签 selenium xpath

我正在尝试使用 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

最佳答案

要切换到下一个 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")

关于selenium - 无法使用 selenium Python 定位元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64683768/

相关文章:

java - 在 Webdriver 中验证页面上的 200 多个列表元素

python - 在 gitlab CI/CD 中使用 selenium

python-3.x - 如何从 Python Selenium 中的类中提取所有 href?

javascript - 如何使用 selenium webdriver、NUnit 和 C# 获取元素属性的子属性值

xpath - 如何找到最后一个元素

XPath:限制结果集的范围

java - selenium webdriver 在 Internet Explorer 中找不到元素错误

python - Lxml html xpath 上下文

c# - 使用 xmldocument 中的 xpath 选择注释之间的节点

java - 如何使用java更改XML节点的值?