gpt4 book ai didi

python - 将 while 语句与 WebDriverWait 和 Expected_conditions 一起使用

转载 作者:行者123 更新时间:2023-12-01 03:57:30 26 4
gpt4 key购买 nike

我正在尝试使用 AJAX 和 jquery 处理网络。我想向下滚动直到到达某个部分,所以我用 wait 和 EC 做了一些方法,但没有成功,如下所示:

 scroll_bottom = """$('html, body').animate({scrollTop:$(document).height()},'fast');"""
from selenium.webdriver.common.by import By
# from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# wait = WebDriverWait(driver,10)
while EC.element_to_be_clickable((By.ID,"STOP_HERE")):
driver.execute_script(scroll_bottom)

有什么方法可以处理等待和EC,以便在某些元素可见和/或可点击之前执行某些操作?

编辑:

我用 JavaScript 做了一些肮脏的把戏,但这绝对不是达到我的目标的 Pythonic 方式。

def scroll_b():
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
driver.execute_script(load_jquery)
wait = WebDriverWait(driver,10)
js = """return document.getElementById("STOP_HERE")"""
selector = driver.execute_script(js)
while not selector :
driver.execute_script(scroll_bottom)
time.sleep(1)
selector = driver.execute_script(js)
print("END OF SCROLL")

最佳答案

这不是内置预期条件的工作方式。一般来说,一旦激活它们,它们就会阻塞,直到任何条件返回 True。

我认为你想要的是自定义的预期条件。这是未经测试的:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

scroll_bottom = """$('html, body').animate({scrollTop:$(document).height()},'fast');"""

def scroll_wait(driver):
# See if your element is present
# Use the plural 'elements' to prevent throwing an exception
# if the element is not yet present
elem = driver.find_elements_by_id("STOP_HERE")

# Now use a conditional to control the Wait
if elem and elem[0].is_enabled and elem[0].is_displayed:
# Returning True (or something that is truthy, like a non-empty list)
# will cause the selenium Wait to exit
return elem[0]
else:
# Scroll down more
driver.execute_script(scroll_bottom)

# Returning False will cause the Wait to wait and then retry
return False

# Now use your custom expected condition with a Wait
TIMEOUT = 30 # 30 second timeout
WebDriverWait(driver, TIMEOUT, poll_frequency=0.25).until(scroll_wait)

这种方法的优点在于,它会在 30 秒(或者您设置的 TIMEOUT 的值)后抛出异常。

关于python - 将 while 语句与 WebDriverWait 和 Expected_conditions 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37195129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com