selenium报错(StaleElementReferenceException: Message: Element not found in the cache...)

今天用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判断一下状态,是否加载完毕

希望大佬可以指点一下~~~

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值