滑动页面查找元素 每次加 300 进度条,总共2次机会
# -*- coding:utf-8 -*- from selenium import webdriver from time import sleep from selenium.common.exceptions import NoSuchElementException driver = webdriver.Chrome(executable_path="chromedriver.exe") driver.maximize_window() driver.get("http://news.baidu.com/") def scroll_find_element(css_element): """滑动查找元素 找到就退出, 没找到就再从头开始找一次""" scroll = 0 loop = 0 while loop <=1: try: driver.find_element_by_css_selector(css_element) except NoSuchElementException: sleep(0.5) js = "document.documentElement.scrollTop={0}".format(scroll) driver.execute_script(js) scroll += 300 else: print("找到元素") break if scroll > 6000: loop += 1 scroll = 0 print("没找到元素 第%s次" %loop) if __name__ == '__main__': scroll_find_element("#star-aside > div.hd > h3") # scroll_find_element("#star-aside > div.hd > h3 lll")