今天用selenium写爬虫时报错了
selenium之 坑(StaleElementReferenceException: Message: Element not found in the cache...)
就是标题中这个错误,然后去网上查了一下
https://blog.csdn.net/huilan_same/article/details/52432206
看到了这篇文章,但是我发现我是另一种情况
就是页面加载太慢了
如果再第二次页面请求之后,加个time.sleep就不会出现问题了
但是为什么会报这个错误我咱是也没什么结论,应该是driver还没有更新对象内容
然后我获取的是上个页面的缓存数据,我也只是猜测
下面代码附上
from selenium import webdriver
import time
driver = webdriver.Firefox()
url = "https://www.huya.com/g/1732"
driver.get(url)
num = 1
while True:
print('第' + str(num) + '页-------------------------------------------------------------------')
html = driver.page_source
names = driver.find_elements_by_xpath('//i[@class="nick"]')
counts = driver.find_elements_by_xpath('//i[@class="js-num"]')
num += 1
# 如果正常请求,这个for循环会出现异常
for name, count in zip(names, counts):
print(name.text + ":" + count.text)
if driver.page_source.find('laypage_next') != -1:
driver.find_element_by_xpath('//a[@class="laypage_next"]').click()
# 加了延时就解决问题了
time.sleep(1)
else:
break
但是这个暂停线程也不是解决问题的办法,鬼知道每次请求页面会消耗多长时间啊,而且会影响性能。我暂时学到这里,还没有学完,以后知道什么其他方法了再更新文章吧,我猜测应该driver判断一下状态,是否加载完毕
希望大佬可以指点一下~~~