You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium测试支付时无法输入Stripe字段,求解决方案

问题分析与修复方案

你的代码里有两个关键问题导致无法和Stripe输入框交互:

1. 重复切换iframe

switch_to_iframe方法中,EC.frame_to_be_available_and_switch_to_it(locator)这个条件本身就会自动把driver切换到目标iframe,不需要再额外调用self.driver.switch_to.frame(iframe),重复切换会导致上下文错乱,后续元素定位自然失败。

修改这个方法:

def switch_to_iframe(self, locator, timeout=5):
    # 该条件已完成iframe切换,无需额外操作
    wait(self.driver, float(timeout)).until(EC.frame_to_be_available_and_switch_to_it(locator))

2. 错误的输入框定位逻辑

切换到卡号iframe后,driver的上下文已经在iframe内部,你不能再用//iframe[@title="Secure card number input frame"]/following-sibling::input这种定位器——这个路径是基于主文档的DOM结构,而iframe内部是独立的DOM环境。

Stripe的卡号输入框在iframe内通常可以用属性直接定位,比如:

# 切换到卡号iframe后,直接定位内部的输入框
sign_in_page.element_is_visible((By.CSS_SELECTOR, '[name="cardnumber"]'), timeout=10).send_keys("4242424242424241")

完整修改后的核心代码片段

# 修改后的BasePage类switch_to_iframe方法
class BasePage:
    # ... 其他方法保持不变
    def switch_to_iframe(self, locator, timeout=5):
        wait(self.driver, float(timeout)).until(EC.frame_to_be_available_and_switch_to_it(locator))

# 测试函数中对应支付输入的部分
sign_in_page.element_is_visible((By.ID, 'cardHolder')).send_keys("John Doe")
# 切换到卡号对应的iframe
sign_in_page.switch_to_iframe((By.XPATH, '//iframe[@title="Secure card number input frame"]'), timeout=10)
# 定位并输入卡号
sign_in_page.element_is_visible((By.CSS_SELECTOR, '[name="cardnumber"]'), timeout=10).send_keys("4242424242424241")
# 若后续需要操作主文档内元素,记得切回主上下文
# self.driver.switch_to.default_content()

额外提醒:Stripe的有效期、CVC等字段通常在各自独立的iframe中,处理时需要分别切换对应iframe,操作完成后切回主文档再进行下一步。

内容的提问来源于stack exchange,提问作者BoGra4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:30:37