Python Selenium Explict等待不会引发TimeoutException

时间:2017-12-04 10:45:05

标签: python selenium phantomjs

browser = webdriver.PhantomJS()
def get_score(url):
    browser.get(url)
    elements = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='shopdsr-score-con']")))
    description_score = float(elements[0].text)
    service_score = float(elements[1].text)
    logistics_score = float(elements[2].text)

关于我的代码。有时这可能会在很长一段时间内停滞不前,如果因为我有这段代码TimeOutException,我会发现它会被wait = WebDriverWait(browser, 30)卡住30秒 但这种情况从未发生过,程序只是在那里等待......问题是什么?

2 个答案:

答案 0 :(得分:0)

使用try,但

除外
   from selenium.common.exceptions import TimeoutException
   from selenium.webdriver.support.ui import WebDriverWait
   from selenium.webdriver.support import expected_conditions as EC

   timeout=30

   try:
       element_present1 = EC.presence_of_element_located((By.XPATH, "//input[@name='username']"))
       WebDriverWait(driver, timeout).until(element_present1)
   except TimeoutException:
       print "Timed out waiting for login page to load"

答案 1 :(得分:0)

正如您所提到的,您已经设置了each,因此您的代码将如下:

WebDriverWait(browser, 30)

逻辑上,您的代码块中没有错误,只有browser = webdriver.PhantomJS() def get_score(url): browser.get(url) elements = WebDriverWait(browser, 30).until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='shopdsr-score-con']"))) description_score = float(elements[0].text) service_score = float(elements[1].text) logistics_score = float(elements[2].text) ,因为当您调用 the program just wait there 网络客户端时,即 get(url) 没有及早返回 PhantomJS Browser document.readyState = "complete" JavaScript 仍在继续加载。因此 AJAX Calls 会拉长。

网络客户端返回 Page Loading document.readyState = "complete" 后,只有 PhantomJS Browser 执行下一行代码:

Selenium

因此程序只是在那里等待一段时间。

更新:

根据您的评论,您需要查看 elements = WebDriverWait(browser, 30).until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='shopdsr-score-con']"))) 的选项,将 pageLoadStrategy 设置为 pageLoadStrategy eager ,根据此质量检查Don't wait for a page to load using Selenium in Python