微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Selenium 中的 NoSuchElementException

如何解决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 放在其下。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。