1. 程式人生 > >python selenium wait方法

python selenium wait方法

any ssi typeerror raise pro 速度 get 例子 height

遇到一個網站運行很慢,所以要等待某個元素顯示出來之後再進行操作,自己手上的書上沒有例子可以直接用

發現一篇文章:http://www.cnblogs.com/yoyoketang/p/6517477.html 原文如下

前言:

在腳本中加入太多的sleep後會影響腳本的執行速度,雖然implicitly_wait()這種方法隱式等待方法一定程度上節省了很多時間。

但是一旦頁面上某些js無法加載出來(其實界面元素經出來了),左上角那個圖標一直轉圈,這時候會一直等待的。

一、參數解釋

1.這裏主要有三個參數:

class WebDriverWait(object):driver, timeout, poll_frequency

2.driver:返回瀏覽器的一個實例,這個不用多說

3.timeout:超時的總時長

4.poll_frequency:循環去查詢的間隙時間,默認0.5秒

以下是源碼的解釋文檔(案例一個是元素出現,一個是元素消失)
def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
"""Constructor, takes a WebDriver instance and timeout in seconds.

:Args:
- driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote)
- timeout - Number of seconds before timing out
- poll_frequency - sleep interval between calls
By default, it is 0.5 second.
- ignored_exceptions - iterable structure of exception classes ignored during calls.
By default, it contains NoSuchElementException only.

Example:
from selenium.webdriver.support.ui import WebDriverWait \n
element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId")) \n
is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ \n
until_not(lambda x: x.find_element_by_id("someId").is_displayed())
"""

二、元素出現:until()

1.until裏面有個lambda函數,這個語法看python文檔吧

2.以百度輸入框為例

技術分享

三、元素消失:until_not()

1.判斷元素是否消失,是返回Ture,否返回False

備註:此方法未調好,暫時放這

技術分享

四、參考代碼:

# coding:utf-8
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Firefox()
driver.get("http://www.baidu.com")
# 等待時長10秒,默認0.5秒詢問一次
WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("kw")).send_keys("yoyo")

# 判斷id為kw元素是否消失
is_disappeared = WebDriverWait(driver, 10, 1).\
until_not(lambda x: x.find_element_by_id("kw").is_displayed())
print is_disappeared

五、WebDriverWait源碼

1.WebDriverWait主要提供了兩個方法,一個是until(),另外一個是until_not()

以下是源碼的註釋,有興趣的小夥伴可以看下

# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException

POLL_FREQUENCY = 0.5 # How long to sleep inbetween calls to the method
IGNORED_EXCEPTIONS = (NoSuchElementException,) # exceptions ignored during calls to the method


class WebDriverWait(object):
def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
"""Constructor, takes a WebDriver instance and timeout in seconds.

:Args:
- driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote)
- timeout - Number of seconds before timing out
- poll_frequency - sleep interval between calls
By default, it is 0.5 second.
- ignored_exceptions - iterable structure of exception classes ignored during calls.
By default, it contains NoSuchElementException only.

Example:
from selenium.webdriver.support.ui import WebDriverWait \n
element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId")) \n
is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ \n
until_not(lambda x: x.find_element_by_id("someId").is_displayed())
"""
self._driver = driver
self._timeout = timeout
self._poll = poll_frequency
# avoid the divide by zero
if self._poll == 0:
self._poll = POLL_FREQUENCY
exceptions = list(IGNORED_EXCEPTIONS)
if ignored_exceptions is not None:
try:
exceptions.extend(iter(ignored_exceptions))
except TypeError: # ignored_exceptions is not iterable
exceptions.append(ignored_exceptions)
self._ignored_exceptions = tuple(exceptions)

def __repr__(self):
return ‘<{0.__module__}.{0.__name__} (session="{1}")>‘.format(
type(self), self._driver.session_id)

def until(self, method, message=‘‘):
"""Calls the method provided with the driver as an argument until the \
return value is not False."""
screen = None
stacktrace = None

end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if value:
return value
except self._ignored_exceptions as exc:
screen = getattr(exc, ‘screen‘, None)
stacktrace = getattr(exc, ‘stacktrace‘, None)
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message, screen, stacktrace)

def until_not(self, method, message=‘‘):
"""Calls the method provided with the driver as an argument until the \
return value is False."""
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if not value:
return value
except self._ignored_exceptions:
return True
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message)

python selenium wait方法