【问题标题】:Selenium Unable to Locate Element by IDSelenium 无法通过 ID 定位元素
【发布时间】:2020-11-09 01:03:09
【问题描述】:

我正在尝试在 CC 的登录页面中输入用户名(和密码)。

但是,Selenium 给了我错误:

“selenium.common.exceptions.NoSuchElementException:消息:无法定位元素:[id="username"]”。

在尝试识别用户名 ID 之前,我让页面加载 5 秒钟,但这没有帮助。我也尝试通过xpath 和name 进行识别,但没有成功。有人知道可能出了什么问题吗?

这是我尝试登录的 CC 网页。

到目前为止,这是我的代码:

def login(url, usernameId, username, passwordId, password, submit_buttonId):
   driver.get(url)
   time.sleep(5)
   driver.find_element_by_id(usernameId).send_keys(username) #username input box not being identified
   driver.find_element_by_id(passwordId).send_keys(password)
   driver.find_element_by_xpath(submit_buttonId).click()

login(
'https://cards.barclaycardus.com/',
'username', myBarclaysUsername,
'password', myBarclaysPassword,
'loginButton'
)

【问题讨论】:

  • 将目标 URL 更改为 https://www.barclaycardus.com/servicing/home?secureLogin= 的简单方法
  • 这完全有效!不过,我也很高兴从其他海报中了解 i frame。

标签: python selenium mozilla


【解决方案1】:
<iframe id="login-iframe" title="Login" src="https://www.barclaycardus.com/servicing/authenticate/home?rnd=120231985&amp;xsessionid=FF4CC3BDD157751E5B9AF5E756D3E303" frameborder="0"></iframe>

你有一个 iframe 切换到它。

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "login-iframe")))

导入

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

【讨论】:

    【解决方案2】:

    有一个iframe,所以你必须切换到它

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait 
    from selenium.webdriver.support import expected_conditions as EC
    
    def login(url, usernameId, username, passwordId, password, submit_buttonId):
       driver.get(url)
       WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "login-iframe")))
    
       time.sleep(5)
    
       driver.find_element_by_id(usernameId).send_keys(username) #username input box not being identified
       driver.find_element_by_id(passwordId).send_keys(password)
       driver.find_element_by_xpath(submit_buttonId).click()
    
    login(
    'https://cards.barclaycardus.com/',
    'username', myBarclaysUsername,
    'password', myBarclaysPassword,
    'loginButton'
    )
    

    【讨论】:

    • 这行得通,但我必须在 iram 开关之前添加一行额外的代码:driver.find_element_by_id('bcus-login-button').click()。此行单击登录按钮,以便您输入用户名和密码的框出现。
    【解决方案3】:

    你试过wait.until吗?看看这样的事情是否有效:

    from selenium import webdriver
    from selenium.webdriver.support import ui
    
    driver = webdriver.Chrome()
    driver.get(url)
    wait.until(lambda driver: driver.find_element_by_id('username'))
    

    【讨论】:

    • 我没有尝试 wait.until 但我确实让浏览器加载了相当长一段时间 uisng time.sleep()。
    猜你喜欢
    • 2020-12-20
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多