TypeError:list indices必须是整数,而不是str Python Error

时间:2017-03-13 04:18:21

标签: python python-2.7

因此我在制作扫描网址并获取响应代码的脚本时收到此错误,然后我收到此错误。我在Stack Overflow,Google等广泛搜索。这个错误的所有答案都与这种情况无关。这可以使陷入同样情况的用户受益。

for dirs in dds_dirpath:
        if responsecode(dds_host + dds_dirpath[dirs]) == "200" or responsecode(dds_host + dds_dirpath[dirs]) == "201" or responsecode(dds_host + dds_dirpath[dirs]) == "202" or responsecode(dds_host + dds_dirpath[dirs]) == "203" or responsecode(dds_host + dds_dirpath[dirs]) == "204" or responsecode(dds_host + dds_dirpath[dirs]) == "205" or responsecode(dds_host + dds_dirpath[dirs]) == "206" or responsecode(dds_host + dds_dirpath[dirs]) == "207" or responsecode(dds_host + dds_dirpath[dirs]) == "208" or responsecode(dds_host + dds_dirpath[dirs]) == "226" or responsecode(dds_host + dds_dirpath[dirs]) == "401":
            print "[   \033[1;32;40mOK\033[1;37;40m   ] ", dds_host + dds_dirpath[dirs]
        else:
            print "[ FAILED ] ", dds_host + dds_dirpath[dirs]

谢谢,所有帮助表示赞赏。我不认为这是一个问题,因为我在同样的情况下找到了无法回答的问题。

1 个答案:

答案 0 :(得分:0)

解决问题的方法是用dds替换dds_dirpath [dirs]。 dds_dirpath [dirs]没有任何意义,因为自己的dirs变量将遍历dds_dirpath并将采用,而不是来自该列表的索引

for dirs in dds_dirpath: 
    if responsecode(dds_host + dirs) == "200" or responsecode(dds_host + dirs) == "201" or responsecode(dds_host + dirs) == "202" or responsecode(dds_host + dirs) == "203" or responsecode(dds_host + dirs) == "204" or responsecode(dds_host + dirs) == "205" or responsecode(dds_host + dirs) == "206" or responsecode(dds_host + dirs) == "207" or responsecode(dds_host + dirs) == "208" or responsecode(dds_host + dirs) == "226" or responsecode(dds_host + dirs) == "401": 
        print "[ \033[1;32;40mOK\033[1;37;40m ] ", dds_host + dirs 
    else: 
        print "[ FAILED ] ", dds_host + dirs

我不能忽视你在if条件下请求一些URL 11次(!)的事实。这很糟糕,因为网站管理员不喜欢来自同一IP的非常频繁的请求,并且可能会禁止您的IP

你应该做这样的事情

for dirs in dds_dirpath:
    if responsecode(dds_host + dirs) in ["200", "201", "202", "203", "204", "205", "206", "207", "208", "226", "401"]: 
        print "[ \033[1;32;40mOK\033[1;37;40m ] ", dds_host + dirs 
    else: 
        print "[ FAILED ] ", dds_host + dirs

你真的把你的响应代码作为字符串,而不是int?