python&selenium 爬虫之页面的等待方法

6 篇文章 0 订阅
2 篇文章 0 订阅
selenium的三种等待方法

页面加载问题
Ajax技术,不确定时间

  • implicitly_wait
    • 一次设置永久有效
    • 元素未加载会一直等待,时间过长
  • WebDriverWait
    • selenium提供得到显示等待模块引入路径
    • 参数 driver - 传入的webdriver实例
    • 参数 timeout - 超时时间:等待的最长时间
    • 参数 poll_frequency - 调用until或者until_not中方法的间隔时间,默认0.5s
    • 参数 ignore_exceptions - 忽略的异常
    • 等待过程中有两个方法,until和until_not
    • method - 每隔一段时间调用这个方法,直到返回值不是FALSE
    • message 超过一定时间 超时抛出异常timeoutException 将message传入异常
  • sleep.time()
    • sleep 线程的休眠
from selenium import webdriver
from time import sleep

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class WaitMethodTest(object):
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.get('http://www.baidu.com')

    def sleep_wait(self):
        self.driver.find_element_by_id('kw').send_keys('three_st')
        sleep(2)
        self.driver.find_element_by_id('su').click()
        sleep(2)
        self.driver.quit()

    def implicitly_wait(self):
        self.driver.implicitly_wait(10)
        self.driver.find_element_by_id('kw').send_keys('three_st')
        self.driver.find_element_by_id('su').click()
        self.driver.quit()

    def webdriver_wait(self):
        wait = WebDriverWait(self.driver, 2)
        wait.until(EC.title_is('百度一下,你就知道'))
        self.driver.find_element_by_id('kw').send_keys('three_st')
        self.driver.find_element_by_id('su').click()
        self.driver.quit()


if __name__ == '__main__':
    case = WaitMethodTest()
    # case.sleep_wait()
    # case.implicitly_wait()
    case.webdriver_wait()

参考链接
  1. 关于selenium中的三种等待方式与EC模块的知识
  2. Selenium EC 与 Wait
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值