【问题标题】:Error while trying to find an element by Xpath in Selenium尝试在 Selenium 中通过 Xpath 查找元素时出错
【发布时间】:2021-08-03 13:01:48
【问题描述】:

错误: selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{"method":"css selector","selector":"#submit-6359ad565c26651cca764d4e291dca49"}

在这个网站上:https://provide-journey-contact-details.homeoffice.gov.uk/next,我收到“保存并继续”按钮的错误,我尝试通过 xpath 找到它,然后通过 css 选择器找到它,但它不起作用。我该怎么办?请帮忙。

driver.find_element_by_xpath(email_address).send_keys("almacompexim@yahoo.com")
driver.find_element_by_xpath(email_verify).send_keys("almacompexim@yahoo.com")
driver.find_element_by_xpath(password).send_keys("Alin1234")
driver.find_element_by_xpath(password_verify).send_keys("Alin1234")
wait = WebDriverWait(driver, 20)
wait.until(EC.visibility_of_element_located((By.XPATH, "//*[contains(@id, 'submit')]"))).click()

【问题讨论】:

  • 找不到页面...

标签: python selenium xpath selenium-chromedriver


【解决方案1】:

我无法打开该页面,但我猜您在访问该元素之前缺少等待/延迟。
此外,6359ad565c26651cca764d4e291dca49 后缀可能是动态的。
试试这个:

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

wait = WebDriverWait(driver, 20)

wait.until(EC.visibility_of_element_located((By.XPATH, "//*[contains(@id,'submit')]"))).click()

如果元素最初不在可见屏幕中,您必须先滚动到它。
像这样:

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

wait = WebDriverWait(driver, 20)
actions = ActionChains(driver)

button = wait.until(EC.presence_of_element_located((By.XPATH, "//*[contains(@id,'submit')]")))
time.sleep(0.5)
actions.move_to_element(button).perform()
time.sleep(0.5)
button.click()

UPD
该元素的唯一 XPath 是

//div[contains(@style,'display')]//div[contains(@style,'display')]//input[@value='Save and continue' and @type='submit']

您也可以使用较短的定位器,但这是唯一地定位该按钮。
因此,您单击该按钮的代码可以是:

wait.until(EC.presence_of_element_located((By.XPATH, "//div[contains(@style,'display')]//div[contains(@style,'display')]//input[@value='Save and continue' and @type='submit']"))).click()

【讨论】:

  • 请将您的代码放入问题中以使其可读
  • 无论如何,该页面没有呈现给我们。也许它仅限于英国 IP
  • gov.uk/provide-journey-contact-details-before-travel-uk。这是网站,您向下滚动一点,现在按开始,然后选中否框,直到看到需要输入电子邮件和密码的页面
  • 现在我明白了。请检查更新的答案
  • 有效!非常感谢,如果耽误了您的时间,我很抱歉,我几乎是初学者!:)
猜你喜欢
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 2022-07-05
  • 2016-10-31
相关资源
最近更新 更多