简体   繁体   English

Python:在列表迭代中途列出索引超出范围

[英]Python: list index out of range halfway through list iteration

First off, list index being out of range does sound simple and self-explanatory... but looking around I can find no explanation for my situation; 首先,列表索引超出范围确实听起来很简单且不言自明......但环顾四周我找不到解释我的情况; I am iterating through a list 19 items long and at the 9th item my console throws the "list index out of range" error". I am at a loss for explanations quite frankly... 我正在遍历列表中的19个项目并且在第9个项目中我的控制台抛出“列表索引超出范围”错误“。我坦白地说明了我的解释...

*I am using phantomjs and selenium to scrape a webpage... THANKS IN ADVANCE! *我正在使用phantomjs和selenium来抓一个网页...感谢提前!

# data list
# -------------------------------------------------------------------------------------   
        xpath = [
        businessName,firstName,lastName,ubi,info,
        licenseType,licenseNumber,licenseEffectiveDate,licenseExpirationDate,status,
        bondProvider,bondNumber,bondAmount,bondEffectiveDate,bondEffectiveDate,insuranceProvider,
        insuranceNumber,insuranceAmount,insuranceEffectiveDate,insuranceExpirationDate
        ] 

        data = [
        "businessName","firstName","lastName","ubi","info",
        "licenseType","licenseNumber","licenseEffectiveDate","licenseExpirationDate","status",
        "bondProvider","bondNumber","bondAmount","bondEffectiveDate","bondEffectiveDate","insuranceProvider",
        "insuranceNumber","insuranceAmount","insuranceEffectiveDate","insuranceExpirationDate"
        ] 
#
#
# xpath check and grab function
# -------------------------------------------------------------------------------------
        i = 0
        while i <= len(data):
           result = browser.find_element_by_xpath(xpath[i]).text    #checks is xpath exists
           print i
           print data[i] + " = " + str(result) 
           i += 1

If, as it appears from your example, the items in xpath and data will always correspond directly to each other, you could do this more easily and cleanly by using the loop expression: 如果从您的示例中看出, xpathdata的项将始终彼此直接对应,则可以使用循环表达式更轻松,更干净地执行此操作:

for elem_xpath, name in zip(xpath, data):

If you need the index i as well, use enumerate : 如果您还需要索引i ,请使用enumerate

for i, (elem_xpath, name) in enumerate(zip(xpath, data)):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM