python - 如何在不刷新页面的情况下修复陈旧元素错误
问题描述
试图在此页面上获取轮胎的详细信息。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
解决方案
澄清:陈旧的元素被抛出,因为该元素不再附加到 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
推荐阅读
- java - Firebase 数据快照返回空值
- node.js - 运行 Electron 应用程序导致 ELIFECYCLE 错误
- azure - 无法将 Azure AD 管理员用户添加到 Enterprise Admins 组
- javascript - Chrome扩展篡改http头可以获取图片,但是无法处理background-image
- css - 无法使用 material-ui 中的类覆盖样式
- r - 使用带有 geom_point 的 for 循环将点添加到现有的 ggplot 对象
- linux - shell 变量包含 ~,它没有被正确解析
- java - android 中的 SQL 数据库,索引 -1 请求大小为 0
- android - 在 newBuild 错误时无法将 sass 渲染到 css
- node.js - 有没有办法在填充对话框流中所需的插槽时触发不同的查询