【问题标题】:How to fix stale element error without refreshing the page如何在不刷新页面的情况下修复陈旧元素错误
【发布时间】:2021-05-11 11:44:10
【问题描述】:

试图在此页面上获取轮胎的详细信息。 https://eurawheels.com/fr/catalogue/INFINY-INDIVIDUAL 。每个轮胎都有不同的FINITIONS。每个FINITIONS的价格和其他细节都不同。我想单击每个 FINITION 类型。问题是在单击 FINITION 类型时,链接会过时,并且您无法刷新页面,如果这样做会将您带回到起始页面。那么,如何在不刷新页面的情况下避免过时元素错误?

     count_added = False
     buttons_div = driver.find_elements_by_xpath('//div[@class="btn-group"]')
     fin_buttons = buttons_div[2].find_elements_by_xpath('.//button')
     fin_count = len(fin_buttons) 
     if fin_count > 2:
            for z in range(fin_count):
                if not count_added:
                    z = z + 2 #Avoid clicking the Title
                    count_added = True
                fin_buttons[z].click()
                finition = fin_buttons[z].text
                time.sleep(2)
                driver.refresh() #Cannot do this. Will take to a different page
                

【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

    澄清:旧元素被抛出是因为该元素不再附加到 DOM。在您的情况下是这样的:buttons_div = driver.find_elements_by_xpath('//div[@class="btn-group"]') 它在 fin_buttons[z].click() 中用作父级

    要解决这个问题,您必须在 DOM 更改后“刷新”元素。你可以这样做:

    from selenium import webdriver
    from time import sleep
    
    
    
    driver = webdriver.Chrome(executable_path="D:/chromedriver.exe")
    
    driver.get("https://eurawheels.com/fr/catalogue/INFINY-INDIVIDUAL")
    
    driver.maximize_window()
    
    driver.find_elements_by_xpath("//div[@class='card-body text-center']/a")[1].click()
    
    
    def click_fin_buttons(index):
        driver.find_elements_by_xpath('//div[@class="btn-group"]')[2].find_elements_by_xpath('.//button')[index].click()
    
    def text_fin_buttons(index):
        return driver.find_elements_by_xpath('//div[@class="btn-group"]')[2].find_elements_by_xpath('.//button')[index].text
    
    sleep(2)
    count_added = False
    buttons_div = driver.find_elements_by_xpath('//div[@class="btn-group"]')
    fin_buttons = buttons_div[2].find_elements_by_xpath('.//button')
    fin_count = len(fin_buttons) 
    if fin_count > 2:
        for z in range(fin_count):
            if not count_added:
                z = z + 2 #Avoid clicking the Title
                count_added = True
            click_fin_buttons(z)
            finition = text_fin_buttons(z)
            sleep(2)
            print(finition)
            #driver.refresh() #Cannot do this. Will take to a different page
    

    【讨论】:

    • 不起作用。仍然给出过时的元素异常。你到底在哪里刷新元素?
    • 嗯,很奇怪,在我这边,它点击了所有没有陈旧元素的 FINITION。这里刷新 FINITIONs:click_fin_buttons(z) 并获取文本 text_fin_buttons(z)
    猜你喜欢
    • 2012-11-23
    • 1970-01-01
    • 2021-06-14
    • 2019-11-25
    • 2017-12-21
    • 2017-05-11
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多