Selenium 中的 NoSuchElementException

问题描述

您好专家! 我是编程新手,我在查找特定元素时遇到了问题。 这是我的代码

from selenium import webdriver
from bs4 import BeautifulSoup as bs
import time

driver = webdriver.Chrome()
driver.get('https://www.ackerwines.com/auctions/?auctionId=1328')
time.sleep(3)
driver.find_element_by_xpath("//label[@for='checkBox']").click()
time.sleep(2)
driver.find_element_by_xpath("(//div[@id='sm-agree-button-wrap'])[3]").click()
time.sleep(5)
try:
    driver.find_element_by_xpath("(//div[@class='elementor-shortcode'])[6]").click()
except:
    driver.find_element_by_xpath("(//a[@class='elementor-icon'])[1]").click()
time.sleep(1)
driver.find_element_by_xpath("//input[@id='xoo-el-username']").click()
driver.find_element_by_xpath("//input[@id='xoo-el-username']").send_keys('malikibrahim6786@gmail.com')
driver.find_element_by_xpath("//input[@id='xoo-el-password']").click()
driver.find_element_by_xpath("//input[@id='xoo-el-password']").send_keys('Malik786')
driver.find_element_by_xpath("//input[@id='xoo-el-rememberme']").click()
driver.find_element_by_xpath("(//button[@type='submit'])[2]").click()
time.sleep(15)

prod = driver.find_element_by_xpath("//div[@class='auctionLotsList']")
print(prod)

我得到的错误

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@class='auctionLotsList']"}
  (Session info: chrome=87.0.4280.88)

解决方法

NoSuchElementException 在 selenium 找不到元素时发生。要解决此问题,请仔细检查元素 xpath 是否正确。导致此问题的另一个问题是网站仍在加载。您可以使用 time.sleep() 添加 1 或 2 秒的延迟。最后,您可以使用 try: 和 except: 捕获异常,方法是将所有 find_by_xpath 放在其下。