虽然循环不会停止

时间:2013-07-02 03:30:12

标签: python loops type-conversion

while start_chapter<=end_chapter:
    os.makedirs("Chapter "+str(start_chapter))
    os.chdir("Chapter "+str(start_chapter))
    chap_url=link+"/c"+str(start_chapter)+"/"
    page=1
    try:
        max_page=get_max_page(chap_url)
    except:
        continue
    while(page<=max_page):
        page_url=chap_url+str(page)+".html"
        try:        
            pic_url=get_pic(page_url)
        except:
            break
        picture_shit=urllib2.urlopen(pic_url).read()
        with open(str(page)+"."+(pic_url.split(".")[len(pic_url.split("."))-1]), 'w') as f: f.write(picture_shit)
        print str(start_chapter)+"::"+str(page)
            page+=1
    os.chdir("../")
    start_chapter+=1

内部while循环不会停止,我测试了页面,看到它已经越过max_page这是23但它根本就没有停止。任何人都可以帮忙吗?提前感谢...

2 个答案:

答案 0 :(得分:9)

max_page是一个字符串,而不是数字。

>>> 1 < '0'
True

答案 1 :(得分:3)

这里有很多问题:

  • 您永远不会增加page,因此它永远不会达到max_page的值(编辑:现已在您的示例中修复)
  • 在编辑中执行上述操作后,只有在文件成功打开时才会发生增量
  • with区块
  • 下面有意图错误
  • max_page不是一个会导致问题的数字,因为Ignacio指出
  • 您拥有的try: continue:块意味着如果分配max_page时出错,则不会再次分配,从而导致比较问题

这可以解决您的大部分问题:

while start_chapter<=end_chapter:
    os.makedirs("Chapter "+str(start_chapter))
    os.chdir("Chapter "+str(start_chapter))
    chap_url=link+"/c"+str(start_chapter)+"/"
    page=1
    try:
        max_page=int(get_max_page(chap_url))
        while(page<=max_page):
            page_url=chap_url+str(page)+".html"
            try:        
                pic_url=get_pic(page_url)
                picture_shit=urllib2.urlopen(pic_url).read()
                with open(str(page)+"."+(pic_url.split(".")[len(pic_url.split("."))-1]), 'w') as f:
                    f.write(picture_shit)
                print str(start_chapter)+"::"+str(page)
            except:
                break
            page+=1
    except:
        continue
    os.chdir("../")
    start_chapter+=1
相关问题