首页 > 解决方案 > Selenium Looped WebDriverWait

问题描述

只想WebDriverWait在嵌套的 for 循环中实现一次。想法是等到它找到价格 ($) 或 5s 然后继续前进,但只在循环中执行一次并在for delta循环中重置for d。OK 循环的第一次迭代for d但是第二次迭代不再等待。它进入if delay但不执行等待。

看起来它不再等待,因为它已经执行了这个(会话代码没有改变?)?我需要迭代等待变量吗?有没有一种干净的方法可以做到这一点?

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


for d in range (0, len(date_array)-duration_max):
    delay = True
    #Other Code

    for delta in range (duration_min,duration_max):

        try:
            if delay:
                wait =WebDriverWait(browser, 5)
                wait.until(EC.text_to_be_present_in_element((By.XPATH,"//*.../div[" + str(date_array[d + delta][2]) + "]/div/div[2]"), "$"))
                delay = False
        except:
            delay = False
            pass


        try:
            date_value = browser.find_element_by_xpath("...").text
            price_value = browser.find_element_by_xpath("...").text

        except:
            pass

等待中调用的 XPath 基于它从 date_array 中提取的 d 和 delta 索引位置始终是唯一的(不确定这是否重要,仅供参考)。

标签: pythonseleniumselenium-webdriver

解决方案


问题说明:

显式等待

它们允许您的代码halt program execution,或freeze the thread,直到condition you pass it resolves.

condition用 a 调用 ,certain frequency直到等待的timeoutelapsed。这意味着只要条件返回一个falsy值,it will keep trying and waiting.

由于显式等待允许您等待条件发生,因此它们非常适合同步浏览器及其 DOM 和 WebDriver 脚本之间的状态。

哪里出错了?

  1. 当您定义 aWebDriverWait时,您可以定义一次并在代码中的任何地方使用引用。

  2. text_to_be_present_in_element适用于:-

""" 检查给定文本是否存在于指定元素中的期望。"""

解决方案

  1. 有一个WebDriverWait像下面这样定义的全局。
  2. 使用visibility_of_element_located而不是text_to_be_present_in_element.

代码 : -

wait = WebDriverWait(browser, 5)
for d in range (0, len(date_array)-duration_max):
    delay = True
    #Other Code
    for delta in range (duration_min, duration_max):
        try:
            if delay:
                some_text = wait.until(EC.visibility_of_element_located((By.XPATH, "//*.../div[" + str(date_array[d + delta][2]) + "]/div/div[2]"))).text
                assert some_text in "$"
                #wait.until(EC.text_to_be_present_in_element((By.XPATH, "//*.../div[" + str(date_array[d + delta][2]) + "]/div/div[2]"), "$"))
                delay = False
        except:
            delay = False
            pass


        try:
            date_value = browser.find_element_by_xpath("...").text
            price_value = browser.find_element_by_xpath("...").text

        except:
            pass

备注:

这将返回一个web element.

wait.until(EC.visibility_of_element_located((By.XPATH, "//*.../div[" + str(date_array[d + delta][2]) + "]/div/div[2]")))

所以你可以使用.textor .send_keysetc 就像你使用它一样driver.find_element


推荐阅读