尝试自动将网址输入Pingdom的网站速度测试(请参阅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
答案 0 :(得分:4)
您可以制作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)