使用selenium,网页长时间加载不完的情况

有一些网页的加载时间很长,新华网直接永远加载不完,但是需要爬取的信息已经加载出来了,如果这时候再等下去就是浪费时间。

将可能出现长时间加载不完的地方try except,

如果网页需要爬取得内容已经加载完毕,即使网页没有加载完成,except之后的driver也可以用

from selenium.common.exceptions import TimeoutException
为什么 from selenium.common.exceptions.TimeoutException as TimeoutException 无法点出TimeoutException

                try:
                    try:
                        driver.get("https://c3.zgdhhjha.com/scholar/")
                    except TimeoutException,e:
                        print type(e)
                        print 'time out in search page'
                    try:
                        driver.find_element_by_id('gs_hdr_tsi').send_keys(line[i])
                        driver.find_element_by_xpath('//*[@id="gs_hdr_tsb"]/span/span[1]').click()
                        a = driver.find_element_by_xpath('//*[@id="gs_res_ccl_mid"]/div/div[2]/div[3]/a[3]')

                    except TimeoutException, e:
                        print 'time out in crawl page'

                    with open('citaresult.txt','a') as wfile:
                        wfile.write(str(i+1)+','+a.text+'\n')

                except Exception, e:# 这里不用,可以判断是否是no such element异常
                    print 'Exception:', e
                    print 'num:', i, 'title:', line[i]
                    driver.close()
                    chromedriver = 'F:\chromedriver_win32\chromedriver.exe'  # chromedriver的路径
                    os.environ["webdriver.chrome.driver"] = chromedriver
                    driver = webdriver.Chrome(chromedriver)





  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值