我正在尝试使用AJAX和jquery来处理网络。我想向下滚动直到达到某个部分,所以我做了一些等待和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")
答案 0 :(得分:1)
这不是内置的预期条件是如何工作的。一般来说,一旦激活它们,它们就会阻塞,直到任何条件都返回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的任何东西)。