小编典典

webdriver等待python中的ajax请求

selenium

目前,我正在编写使用ajax进行搜索的webdriver测试。如果在键入搜索内容之后并按Enter键之前添加显式等待,则测试效果很好。

wd.find_element_by_xpath("//div[@class='searchbox']/input").send_keys("obama")
time.sleep(2)
wd.find_element_by_xpath("//div[@class='searchbox']/input").send_keys(Keys.RETURN)

wd.find_element_by_xpath("//div[@class='searchbox']/input").send_keys("obama")
wd.find_element_by_xpath("//div[@class='searchbox']/input").send_keys(Keys.RETURN)

失败。我正在使用1个虚拟CPU在ec2上运行测试。我怀疑,即使在发送与搜索相关的GET请求之前,我也按回车键;如果在建议之前按回车键,它将失败。

有没有更好的方法来添加显式等待?


阅读 340

收藏
2020-06-26

共1个答案

小编典典

您确实可以添加一个明确的等待,以等待诸如

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0

ff = webdriver.Firefox()
ff.get("http://somedomain/url_that_delays_loading")
ff.find_element_by_xpath("//div[@class='searchbox']/input").send_keys("obama")

try:
    element = WebDriverWait(ff, 10).until(EC.presence_of_element_located((By.ID, "keywordSuggestion")))
finally:
    ff.find_element_by_xpath("//div[@class='searchbox']/input").send_keys(Keys.RETURN)
    ff.quit()

请参阅:http :
//docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#explicit-and-implicit-
waits

2020-06-26