IndentationError:期望while循环中的缩进块

时间:2015-06-12 15:06:27

标签: python

当我尝试从多个网站进行网络搜索时出现此错误

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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

您收到该错误是因为您没有缩进。 Python需要严格缩进作为代码块分隔符。试试这个:

i=0
n=len(urls)

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

答案 2 :(得分:0)

你有缩进错误,这意味着,你的某些子块需要在它之前有4个空格,这在你的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