【问题标题】:Selenium does not load html properly - Python3.8 [duplicate]Selenium 无法正确加载 html - Python3.8 [重复]
【发布时间】:2020-03-26 00:36:42
【问题描述】:

我正在使用 selenium 和 python 来注册一个网站。 我的问题是,当我需要插入信用卡号和安全号码时,虽然我复制了字段的 xpath,但等待字段可见且可点击,python 引发超时异常,因为他没有找到任何字段用那个xpath。该字段的html代码是:

<input id="cardnumber" autocomplete="cc-number" type="tel" pattern="[0-9]*" placeholder="1111 2222 3333 4444" data-encrypted-name="number" class="form-control">

更新:也许我明白了。 当我打印出 driver.page_source 时,我注意到它没有正确加载,现在我明白为什么 Selenium 什么都找不到,无论是通过 xpath,也不是通过名称或所有内容。我注意到加载的内容可以全部点击,但是有些字段没有加载。 那么为什么 Selenium 会这样呢?

再次更新:已解决,解决方法是我每次都需要切换 iframe。

【问题讨论】:

  • 请考虑发布您找到的解决方案作为答案并接受它。

标签: python-3.x selenium


【解决方案1】:

通过添加一些等待来试试这个:

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



driver = webdriver.Chrome()
driver.maximize_window()
driver.get("Your Website")
try:
    cardnumber = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, "#cardnumber")))
except:
    print('Sorry!')


cardnumber.send_keys('XXXXX')

【讨论】:

    【解决方案2】:

    您传递了错误的 ID。当您尝试使用其 ID 识别元素时,您不需要传递 #

    cardnumber = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, "cardnumber")))
    

    请检查定位器策略:https://selenium-python.readthedocs.io/locating-elements.html

    【讨论】:

    • 我已经尝试过,使用 xpath(如我所说),通过 id、名称,没有任何效果。
    猜你喜欢
    • 2012-05-25
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    相关资源
    最近更新 更多