如何让Selenium WebDriver等到<dd>元素包含数据后再继续?

2024-06-16 10:24:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试自动将一个url输入到Pingdom的网站速度测试(参见http://tools.pingdom.com/fpt/),然后提取并打印测试结果。在

我写了一些代码,但我不知道如何从Perf中获取数据。grade'元素。在

这个元素似乎在测试运行之前就存在了(我猜是在服务器端运行?)但是是空的。然后,一旦测试完成,就用值填充元素。在

如何让Selenium在填充此值之后再尝试打印它?在

这是我的代码:

import datetime
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

# Pingdom Website Speed Test
for i in range(0, 1):

    # Initialises chromedriver
    driver = webdriver.Chrome(executable_path=r'C:\Users\Desktop\Python\chromedriver\chromedriver.exe')

    # Opens Pingdom homepage
    driver.get('http://tools.pingdom.com/fpt/')

    # Looks for search box, enters 'http://www.url.com/' and submits it
    pingdom_url_element = driver.find_element_by_id('urlinput')
    pingdom_url_element.send_keys('http://www.url.com/')
    pingdom_test_button_element = "//button[@tabindex='2']"
    driver.find_element_by_xpath(pingdom_test_button_element).click()

    # Waits until page has loaded then looks for attribute containing the report score's value and returns the value
    pingdom_performance_result = WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.XPATH, "//div[@id='rt_sumright']/dl[@class='last']/dd[1]")))

    print('Pingdom score:')
    print(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S"), "---", pingdom_performance_result.text)

    driver.close()

    i += 1

Tags: fromimportcomhttpurl元素fordatetime
1条回答
网友
1楼 · 发布于 2024-06-16 10:24:58

您可以生成一个custom expected condition并等待等级有一个值,或者在本例中匹配特定的正则表达式:

from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support import expected_conditions as EC

class wait_for_text_to_match(object):
    def __init__(self, locator, pattern):
        self.locator = locator
        self.pattern = pattern

    def __call__(self, driver):
        try:
            element_text = EC._find_element(driver, self.locator).text
            return self.pattern.search(element_text)
        except StaleElementReferenceException:
            return False

用法:

^{pr2}$

相关问题 更多 >