首页 > 解决方案 > 如何在不刷新页面的情况下修复陈旧元素错误

问题描述

试图在此页面上获取轮胎的详细信息。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
                

标签: pythonseleniumweb-scraping

解决方案


澄清:陈旧的元素被抛出,因为该元素不再附加到 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

推荐阅读