在标题中动态查找元素,并单击它们以在python selenium中进行验证

在标题中动态查找元素,并单击它们以在python selenium中进行验证,python,python-3.x,selenium,automation,Python,Python 3.x,Selenium,Automation,这是我的密码 from selenium import webdriver from selenium.webdriver.common.by import By class Runfftest(): def test(self): """ Inistitate the ff browser launch the browser :return: """ baseUrl = "https:/

这是我的密码

from selenium import webdriver
from selenium.webdriver.common.by import By

class Runfftest():
    def test(self):
        """
        Inistitate the ff browser
        launch the browser
        :return:
        """
        baseUrl = "https://letskodeit.teachable.com/p/practice"
        driver = webdriver.Firefox(executable_path="/usr/local/bin/geckodriver")
        driver.maximize_window()
        driver.get(baseUrl)
        driver.implicitly_wait(10)

        header_by_xpath = driver.find_element_by_xpath("//*[@id='navbar']")
        links_in_header = header_by_xpath.find_elements(By.TAG_NAME,"a")
        size_of_links = len(links_in_header)
        print(size_of_links)

        for linkinheader in links_in_header:
            linkinheader.click()


ff = Runfftest()
ff.test()

我可以找到一个元素并单击它,但当我找到它时,它会抛出一个错误。

第一次单击后,您的错误是:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
这意味着单击后,您将获得全新的html页面,并且旧页面中的所有元素都已过时(新页面上不存在)

请注意,标题中的链接列表包含元素列表,但不包含链接(URL)本身。因此,您可以这样做(而不是单击):


所以我不明白一件事,您通过xpath查找元素,为什么在搜索标题并尝试单击标题之后

遵循这一准则,它是有效的; ps您甚至选择了错误的xpath:

from selenium import webdriver
from selenium.webdriver.common.by import By

class Runfftest():
    def test(self):
        """
        Inistitate the ff browser
        launch the browser
        :return:
        """
        baseUrl = "https://letskodeit.teachable.com/p/practice"
        driver = webdriver.Firefox(executable_path="/usr/local/bin/geckodriver")
        driver.get(baseUrl)
        driver.implicitly_wait(10)
        header_by_xpath = driver.find_element_by_xpath(".//*[@id='navbar']/div/div/a")
        header_by_xpath.click()

ff = Runfftest()
ff.test()
PS:完成后请记住关闭浏览器:

driver.close()

哪个错误?请在你的问题中贴出错误。你的错误在哪里?把它贴在你的问题上。
driver.close()