“元素未附加到页面文档”添加隐式等待Selenium自动化后引发预期

bakd9h0s  于 2022-12-18  发布在  其他
关注(0)|答案(2)|浏览(147)

我在代码中添加了隐式等待,它会导致错误“Message:过时的元素引用:元素未附加到页面文档”
下面是代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time

service_obj = Service("C:/Users/divya/Downloads/chromedriver_win32/chromedriver.exe")
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=service_obj)

driver.implicitly_wait(5)
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/")
driver.find_element(By.CSS_SELECTOR, ".search-keyword").send_keys("ber")
# time.sleep(2)

products = driver.find_elements(By.XPATH, "//div[@class='products']/div")
count = len(products)
assert count > 0

for product in products:
    product.find_element(By.XPATH, "div/button").click() #=======ERROR HERE=============

driver.find_element(By.CSS_SELECTOR, ".cart-icon").click()
driver.find_element(By.XPATH, "//button[text()='PROCEED TO CHECKOUT']").click()
# time.sleep(3)
driver.find_element(By.XPATH, "//input[@type='text']").send_keys("rahulshettyacademy")
driver.find_element(By.CSS_SELECTOR, ".promoBtn").click()

Sleep()函数可以代替隐式等待正常工作。
任何人有相同的建议/理由。请指导

6gpjuf90

6gpjuf901#

我认为这个问题是因为页面正在刷新,或者元素在被定位之后但在被单击之前从DOM中删除
为了解决这个问题我建议

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

...

for product in products:
    element = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "div/button"))
    )
    element.click()
...

并除去了

driver.implicitly_wait(5)
y1aodyip

y1aodyip2#

搜索后需要等待一段时间:

driver.get("https://rahulshettyacademy.com/seleniumPractise/#/")
driver.find_element(By.CSS_SELECTOR, ".search-keyword").send_keys("ber")
time.sleep(1)

products = driver.find_elements(By.XPATH, "//div[@class='products']/div")
count = len(products)
assert count > 0

i = 0
for i in range(len(products)):
    driver.find_element(By.XPATH, "(//div[@class='products']//button)[" + str(i + 1) + "]").click()

driver.find_element(By.CSS_SELECTOR, ".cart-icon").click()
driver.find_element(By.XPATH, "//button[text()='PROCEED TO CHECKOUT']").click()
time.sleep(1)
driver.find_element(By.XPATH, "//input[@type='text']").send_keys("rahulshettyacademy")

driver.find_element(By.CSS_SELECTOR, ".promoBtn").click()

相关问题