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

时间:2016-02-22 04:33:19

标签: python list web-scraping

首先,列表索引超出范围听起来简单且不言自明......但环顾四周我找不到解释我的情况;我正在遍历列表中的19个项目,在第9个项目中,我的控制台会将"列表索引超出范围"错误&#34 ;.坦率地说,我无法解释......

*我正在使用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

1 个答案:

答案 0 :(得分:3)

如果从您的示例中看出,xpathdata中的项目将始终直接相互对应,则可以使用循环表达式更轻松,更干净地完成此任务:

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

如果您需要索引i,请使用enumerate

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