【问题标题】:Selenium find_element_by_css_selector to fire before the page has fully loadedSelenium find_element_by_css_selector 在页面完全加载之前触发
【发布时间】:2017-11-21 16:45:22
【问题描述】:

我有一个基本的 python 脚本来测试网站页面速度。基本上它会加载一个页面,检查一个元素是否可见,然后记录这两个事件之间所用的时间。

我用它来检查元素是否可见:

def wait_for_visibility(selector, timeout_seconds=10):
retries = timeout_seconds
while retries:
    try:
        element = browser.find_element_by_css_selector(selector)
        if element is not None:
            return element
    except:
        if retries <= 0:
            raise
        else:
            pass

    retries = retries - 1
raise Exception(
    "Element %s not visible despite waiting for %s seconds" % (
        selector, timeout_seconds)
)

我使用这个顺序:

    test_times['page_pre_' + name] = time.time()

    browser.get(base + path)

    wait_for_visibility(selector=selector_dict[page], timeout_seconds=240)

    test_times['page_post_' + name] = time.time()

我的问题是 find_element_by_css_selector 似乎直到页面(更具体地说是它应该查找的元素)已经完成加载几秒钟后才完成并返回。这确实降低了我的脚本作为速度测试的有效性。

有问题的页面非常大,并且是使用 Vue 组件构建的,如果这是导致问题的原因,那么有没有其他方法可以使用 selenium 来查找特定的页面加载事件?

【问题讨论】:

标签: python selenium testing webdriver performance-testing


【解决方案1】:

我设法解决了检查之前未加载的元素的问题,而不使用我自己的循环但使用了预期的条件,这是我使用的代码

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

...

try:
    element_present = EC.presence_of_element_located((By.CSS_SELECTOR, string))
    WebDriverWait(driver, timeout).until(element_present)
    return driver.find_elements_by_css_selector(string)
except TimeoutException:
    print "Timed out waiting for page to load"
    driver.quit()

基本上你以秒为单位指定超时,expected_conditions 将使 WebDriver 等待,直到满足预期条件或时间到。在我的情况下,这比我自己的等待元素函数要快,它可能会加快你的脚本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-05
    • 2014-08-27
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多