Selenium 爬取豆瓣电影评论时 NoSuchElementException 错误解决方法
在使用 Selenium 爬取豆瓣电影评论时,可能会遇到 NoSuchElementException 错误,提示找不到指定的元素。这个错误通常是由于页面加载不完全或者元素定位方式不正确导致的。
错误信息:
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/14熊俊豪.py", line 15, in <module>
all_comment_btn = driver.find_element(By.CSS_SELECTOR,'#comments > div:nth-child(1) > div.comment > p > span')
File "C:\Python3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Python3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Python3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"#comments > div:nth-child(1) > div.comment > p > span"}
(Session info: chrome=96.0.4664.93)
解决方法:
-
增加等待时间: 可以尝试增加等待时间,让页面完全加载后再查找元素。
-
修改元素定位方式: 可以尝试使用其他定位方式,如使用 XPath 定位元素。
-
检查元素是否存在: 可以先手动打开页面,在浏览器中检查元素是否存在,如果不存在则需要修改定位方式。
代码示例:
url = 'https://movie.douban.com/subject/25868125/'
driver.get(url)
time.sleep(10) # 等待页面加载
all_comment_btn = driver.find_element(By.XPATH, '//*[@id="comments"]/div[1]/div[2]/p/span/a')
all_comment_btn.click()
time.sleep(10) # 等待页面加载
这里使用了 XPath 定位方式,同时增加了等待时间,以确保页面完全加载后再查找元素。另外,由于页面结构可能会变化,所以需要根据实际情况进行定位元素。
原文地址: https://www.cveoy.top/t/topic/oBbN 著作权归作者所有。请勿转载和采集!