python - 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 索引位置始终是唯一的(不确定这是否重要,仅供参考)。
解决方案
问题说明:
显式等待
它们允许您的代码halt program execution
,或freeze the thread
,直到condition you pass it resolves
.
condition
用 a 调用 ,certain frequency
直到等待的timeout
是elapsed
。这意味着只要条件返回一个falsy
值,it will keep trying and waiting.
由于显式等待允许您等待条件发生,因此它们非常适合同步浏览器及其 DOM 和 WebDriver 脚本之间的状态。
哪里出错了?
当您定义 a
WebDriverWait
时,您可以定义一次并在代码中的任何地方使用引用。text_to_be_present_in_element
适用于:-
""" 检查给定文本是否存在于指定元素中的期望。"""
解决方案
- 有一个
WebDriverWait
像下面这样定义的全局。 - 使用
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]")))
所以你可以使用.text
or .send_keys
etc 就像你使用它一样driver.find_element
推荐阅读
- java - 如何在android中解决“尝试重新打开关闭的SQLite数据库”
- java - 在 Liferay 中使用 OkHttp 来使用外部的 REST API。OSGi 的问题
- c# - Newtonsoft.Json.JsonSerializationException('从'Goodbuy.Models.product'上的'Id'获取值时出错。')将领域对象序列化为json
- excel - Excel 2019 - 如何使用 VBA 检测在 Excel 主菜单“文件”下拉菜单上所做的选择?
- java - 我断言在 Java 中不会发生错误。我该如何编码?
- android - 如何在 Retrofit Android 中使用 JSON 响应管理模型类?
- haskell - 将函数应用于 Haskell 中的元素列表
- c++ - 将泛型函数分配给函数指针 struct memeber
- tensorflow - 检查Tensorflow中的类分布?
- javascript - NodeJS:获取文件夹中的图像文件大小,如果图像太大则压缩