简体   繁体   English

告诉硒在预期条件后停止阻断

[英]Telling selenium to stop blocking after expected condition

I am interested in one element, let's call it 我对一个元素感兴趣,我们称之为

<div class="ofInterest" some-attr="dataIReallyWant"></div>

When I switch off js in firefox, this element does not exist. 当我在firefox中关闭js时,此元素不存在。 With javascript it does. 使用javascript可以。 I could not tell how it was being generated but my guess is that there is an ajax call which returns a js file which executes this javascript. 我不知道它是如何生成的,但是我猜是有一个ajax调用返回一个执行此javascript的js文件。

I am using selenium but it is very slow. 我正在使用硒,但是速度很慢。 I want to tell Selenium this: 我想告诉硒:

  1. Wait for this element to load, ie something like EC.visibility_of_element_located((By.CSS, '.ofInterest')) 等待此元素加载,例如EC.visibility_of_element_located((By.CSS, '.ofInterest'))

  2. once you detect said element, stop blocking the code and don't download any further so don't waste my bandwidth 一旦您检测到所说的元素,就不要再阻止代码了,不要再下载了,所以不要浪费我的带宽

Simply wait for the element to exist in the DOM, then either quit/close the browser or execute some JavaScript to stop the page from loading: 只需等待DOM中存在该元素,然后退出/关闭浏览器或执行一些JavaScript来阻止页面加载:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until( #10 second timeout.
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()
    # OR
    #driver.execute_script("window.stop();")

More information can be found here. 可以在此处找到更多信息

Explicit waits were made exactly for what you are describing: 确切的等待正是针对您所描述的内容:

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. 显式等待是您定义的代码,用于等待特定条件发生后再继续执行代码。 The worst case of this is time.sleep(), which sets the condition to an exact time period to wait. 最糟糕的情况是time.sleep(),它将条件设置为要等待的确切时间段。

In the worst case scenario, you would wait X amount of seconds that you've passed to the WebDriverWait , 10 seconds in this case: 在最坏的情况下,您将等待X秒钟的时间(已传递给WebDriverWait ,这种情况下需要10秒钟:

element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )

But, if the element is found earlier, it would give you the element and stop blocking the execution. 但是,如果较早找到该元素,它将为您提供该元素并停止阻止执行。 By default, it checks for the expected condition every 500ms. 默认情况下,它每500毫秒检查一次预期条件。

FYI, under-the-hood, it is just a while True: loop : 仅供参考,在幕后,只有一段while True: loop

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM