簡體   English   中英

IndentationError:期望while循環中出現縮進的塊

[英]IndentationError: expected an indented block in while loop

當我嘗試從多個網站抓取網頁時出現此錯誤

import urllib
urls = ["http://google.com","http://cnn.com"]

i=0
n=len(urls)

while i< n:
htmlfile = urllib.urlopen(urls[i])
htmltext =htmlfile.read()
print htmltext
i=i+1

錯誤

  PS C:\python> python basic1.py
  File "basic1.py", line 9
  htmlfile = urllib.urlopen(urls[i])
  IndentationError: expected an indented block
import urllib 

urls = ["http://google.com","http://cnn.com"]

i=0
n=len(urls)

while i < n:
   htmlfile = urllib.urlopen(urls[i])
   htmltext =htmlfile.read()
   print htmltext
   i=i+1

您收到該錯誤是因為您沒有縮進。 Python需要嚴格縮進作為代碼塊分隔符。 嘗試這個:

i=0
n=len(urls)

while i< n:
    htmlfile = urllib.urlopen(urls[i])
    htmltext =htmlfile.read()
    print htmltext
    i=i+1

您有縮進錯誤,這意味着,您某些子塊之前需要具有4spaces,這在您的while代碼塊中很明顯,這是正確的方法:

import urllib
urls = ["http://google.com","http://cnn.com"]

i=0
n=len(urls)

while i< n:
    htmlfile = urllib.urlopen(urls[i])
    htmltext =htmlfile.read()
    print htmltext
    i=i+1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM