我正在 selenium 中编写 while 循环,并希望对 while 循环进行条件设置,这样当滚动条滚动到末尾时,while 循环应该停止。我如何在 while 循环中编写这种类型的条件?我正在使用 Keys.DOWN,而我的 while 循环现在设置为 True
我的 while 循环代码:
while True: self.driver.find_element_by_id('pane-side').send_keys(Keys.DOWN * 5) self.driver.find_elements_by_xpath("//div[@class='_2wP_Y']")
如果您想在 while 循环中滚动,您可以检查使用后页面 Y 偏移量是否发生变化send_keys(Keys.DOWN * 5)
send_keys(Keys.DOWN * 5)
from time import sleep # Offset can not be smaller then 0 # we just want to ensure that we will try to scroll down at least once previous_offset = -1 # current_offset (most probably 0) current_offset = self.driver.execute_script('return window.pageYOffset;') while previous_offset!=current_offset: previous_offset = current_offset self.driver.find_element_by_id('pane-side').send_keys(Keys.DOWN * 5) # Give a browser some small time to react sleep(0.1) current_offset = driver.execute_script('return window.pageYOffset;')
如果你不需要使用循环并且想要向下滚动到页面末尾,那么你可以这样做
self.driver.execute_script('window.scrollTo(0,document.body.scrollHeight);')