Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python selenium webdriver:列表索引超出范围_Python_Selenium_Selenium Webdriver - Fatal编程技术网

Python selenium webdriver:列表索引超出范围

Python selenium webdriver:列表索引超出范围,python,selenium,selenium-webdriver,Python,Selenium,Selenium Webdriver,我有以下代码来向下滚动启用javascript的网站。问题是当newHeight达到大约229275时,我在浏览器的行中得到了超出范围的列表。按类名称('alt')[0]查找元素。单击()。但是为什么我会出现这个错误,我该如何解决这个问题呢 我的代码: browser = webdriver.PhantomJS("phantomjs") browser.get(url) while True: time.sleep(pause)

我有以下代码来向下滚动启用javascript的网站。问题是当
newHeight
达到大约
229275
时,我在
浏览器的行中得到了超出范围的列表。按类名称('alt')[0]查找元素。单击()。但是为什么我会出现这个错误,我该如何解决这个问题呢

我的代码:

browser = webdriver.PhantomJS("phantomjs")
    browser.get(url)
        while True:            
         time.sleep(pause)
         newHeight = browser.execute_script("return document.body.scrollHeight")
         print newHeight
         browser.find_elements_by_class_name('alt')[0].click()

只需try/except语句

browser = webdriver.PhantomJS("phantomjs")
browser.get(url)
    while True:   
     try:
        time.sleep(pause)
        newHeight = browser.execute_script("return document.body.scrollHeight")
        print newHeight
        browser.find_elements_by_class_name('alt')[0].click()
     except:
        pass

我建议在采取行动之前先检查一下清单

browser = webdriver.PhantomJS("phantomjs")
browser.get(url)
while True:            
    time.sleep(pause)
    newHeight = browser.execute_script("return document.body.scrollHeight")
    print newHeight
    alt_elements = browser.find_elements_by_class_name('alt')
    if len(alt_elements):
        alt_elements[0].click()

只是一个旁注,无限的while循环可能是一件危险的事情。

尝试向下滚动页面并使用以下方法单击元素:

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException

browser = webdriver.PhantomJS("phantomjs")
browser.get(url)
while True:
    browser.find_element_by_tag_name("body").send_keys(Keys.END)
    try:
        wait(browser, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "alt"))).click()
    except NoSuchElementException:
        break

这应该允许您单击所需元素,以防找到它或打破循环,否则

在调用
按类查找元素时,该元素在页面中不存在。它要么已经不存在,要么还不存在。尝试等待它或处理它不再存在的情况。