【问题标题】:Unable to locate element: Selenium无法定位元素:硒
【发布时间】:2020-07-23 15:58:57
【问题描述】:

我想通过点击选择更多信息链接。我已经尽我所能,但每次错误 NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector" 弹出.

起初,我想可能是因为我没有正确更改选项卡,这就是显示此错误的原因。但是,即使在使用 window_handles 之后,我仍然无法在此页面上找到任何元素。

帮助

self.driver.window_handles
        base = self.driver.window_handles[0]        
        child = self.driver.window_handles[1]

        window_set = {self.driver.window_handles[0], self.driver.window_handles[1]}

for x in window_set:
        if(base != x):
            self.driver.switch_to.window(x)
            self.driver.find_element_by_id("mc-lnk-moreInfo").click() 

【问题讨论】:

  • 完成编辑...
  • 希望它不在 iframe 元素中

标签: selenium selenium-webdriver automation selenium-chromedriver nosuchelementexception


【解决方案1】:

请使用包含和 ID 检查以下解决方案

包含包含的 Xpath

 element= WebDriverWait(self.driver, 30).until(
            EC.element_to_be_clickable((By.XPATH, '//*[contains(text(), 'More information')]')))

 self.driver.execute_script("arguments[0].click();", element)

带有 ID 的 Xpath

element= WebDriverWait(self.driver, 30).until(
        ec.element_to_be_clickable((By.ID, "//a[@id='mc-lnk-moreInfo']")))

 self.driver.execute_script("arguments[0].click();", element)

工作解决方案:

driver = webdriver.Chrome(executable_path=r"C:\New folder\chromedriver.exe")
driver.maximize_window()
wait = WebDriverWait(driver, 10)
driver.get("your url")
childframe = wait.until(EC.presence_of_element_located((By.NAME, "mainFrame")))
driver.switch_to.frame(childframe)
element=wait.until(EC.element_to_be_clickable((By.ID, "mc-lnk-moreInfo")))
print element.text
element.click()

注意:请在您的解决方案中添加以下导入

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

输出:

【讨论】:

  • 我希望它不在 iframe 框内,并且您在正确的窗口中
  • 如果可能的话,我可以检查你的网址吗?
  • 我看到我要点击的元素在框架内。问题是这个框架没有 ID。我不认为 XPATH 可以访问框架
  • 您可以使用框架索引来做到这一点,但如果您在页面中签入多个框架,并且还有不同的方法来识别框架,就像我对 NAME 所做的那样。你会愿意accept 回答你的问题吗?
【解决方案2】:

尝试wait for the element然后点击它

替换

self.driver.find_element_by_id("mc-lnk-moreInfo").click()

有关注

  self.more_info = WebDriverWait(self.driver, 30).until(
        ec.visibility_of_element_located((By.ID, "//a[@id='mc-lnk-moreInfo']")))
    ActionChains(self.driver).move_to_element(self.more_info).click().perform()

在您的导入中添加以下内容

from selenium.webdriver import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec

【讨论】:

  • 那么,我应该在我的代码中的for循环中编写这段代码吗?
  • 另外,我已经在这段代码之前给了一个 sleep(5) 。所以我认为在点击发生之前已经让执行等待
  • 好的,你试过find_element_by_id("//a[@id='mc-lnk-moreInfo']")吗?没有实时链接我无法测试,你能分享链接吗?
猜你喜欢
  • 2019-09-30
  • 1970-01-01
  • 2021-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2019-12-01
相关资源
最近更新 更多