【问题标题】:IndexError: list index out of range Not getting SolvedIndexError:列表索引超出范围未解决
【发布时间】:2017-06-08 16:23:24
【问题描述】:
import glob
from bs4 import BeautifulSoup
f = open('csvfile.csv','w')
for file in glob.glob('*.htm'):
    print 'Processing', file
    for y in range(0,3):          
        for x in range(0, 6): 
            soup = BeautifulSoup(open(file).read())
            all_string=soup.find_all("h2")[x].get_text()
            #stack=[]
            #acct.write(", ".join(stack) + '\n')
            f.write(all_string) 
            f.write('\n')
            print(all_string)
    x=0  
f.close() 

输出-

通过 N2 衍生的氮化铁和酰亚胺处理碱控制的 C-H 裂解或 N-C 键形成 - 美国化学学会杂志(ACS 出版物).htm
摘要
支持信息
环境反应条件下钒催化分子二氮还原为甲硅烷胺

Traceback(最近一次调用最后一次):

文件“”,第 1 行,在 runfile('/Users/ROXX/Desktop/project/csv1.py', wdir='/Users/ROXX/Desktop/project')

文件 "/Users/ROXX/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", 第 880 行,在运行文件中 execfile(文件名,命名空间)

文件 "/Users/ROXX/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", 第 94 行,在 execfile 中 builtins.execfile(filename, *where)

文件“/Users/ROXX/Desktop/project/csv1.py”,第 17 行,在 all_string=soup.find_all("h2")[x].get_text()

IndexError: 列表索引超出范围

【问题讨论】:

    标签: python-2.7


    【解决方案1】:

    错误的原因可能是您正在处理的文件中出现的 h2 少于 7 次(在第二个循环中)。重复“all_string”而不是固定间隔可能会解决问题。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多