用python、selenium爬取网页时出现一下错误:
NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="container"]/div/div/div[2]/h1"}
(Session info: headless chrome=102.0.5005.63)
错误原因:
脚本执行到“xpath”这一行代码时,对应页面上的元素还没加载完成,因此报错。
解决方法:
#coding:utf-8
from selenium import webdriver
import selenium.webdriver.support.ui as ui
driver = webdriver.Chrome()
# driver = webdriver.Chrome(chrome_options=chrome_options) # 也可用driver = webdriver.Chrome()
driver.get('http://www.xxxxx.com')
wait = ui.WebDriverWait(driver,9)
wait.until(lambda driver: driver.find_element_by_xpath("//span[text()='你好']"))
driver.find_element_by_xpath("//span[text()='你好']").click()
'''
import selenium.webdriver.support.ui as ui
wait = ui.WebDriverWait(driver,5)
wait.until(lambda driver: driver.find_element_by_xpath("//span[text()='你好']"))
其中这3行代码,表示会反复调用until中的函数,找到就返回,超过9秒就抛出Timeout异常:TimeoutException。
'''