【问题标题】:How can I get Selenium WebDriver to wait until <dd> element contains data before proceeding?如何让 Selenium WebDriver 等到 <dd> 元素包含数据后再继续?
【发布时间】:2016-05-18 19:50:15
【问题描述】:

我正在尝试自动为 Pingdom 的网站速度测试提供一个 url(请参阅 http://tools.pingdom.com/fpt/),然后提取并打印该测试的结果。

我已经编写了一些代码,但我不知道如何从“Perf.等级'元素。

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

如何让 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

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    您可以创建 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
    

    用法:

    import re
    
    wait = WebDriverWait(driver, 60)
    pattern = re.compile(r"\d+/\d+")
    pingdom_performance_result = wait.until(wait_for_text_to_match((By.XPATH, "//div[@id='rt_sumright']/dl[@class='last']/dd[1]"), pattern))
    
    print(pingdom_performance_result.text)
    

    【讨论】:

    • 太好了,感谢这个解决方案,效果很好!唯一的小事是 PyCharm 告诉我 StaleElementReferenceException 是一个未解决的引用。知道为什么吗?
    • @chewflow 啊,当然,添加了导入语句。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 2014-12-17
    • 2016-09-20
    • 2011-07-04
    • 1970-01-01
    • 2016-07-18
    • 2014-11-03
    • 1970-01-01
    相关资源
    最近更新 更多