urls是一个列表,因此有一个索引。为了访问列表中的值,您必须通过其索引来访问。让我演示一下:
>>> urls = ['hello', 'world']
>>> urls[0]
'hello'
>>> urls[1]
'world'
>>> len(urls)
2
>>>
请注意,索引是0基于的(意味着第一个元素是通过 访问的0,然后1是第二个元素)。这就是为什么您的while语句中的条件读取while i < len(url),因为i正在访问索引,并且由于索引0从而不是开始1,您只能继续它直到1它是列表中的第二个值。
2让我通过放入索引值来演示如果超出范围会发生什么:
>>> urls[2]
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
urls[2]
IndexError: list index out of range
>>>
如您所见,您得到一个IndexError.
但是,在您的情况下,有一种更好的方法可以使用循环来遍历listurl for:
# This look will go through all the values inside your list, and the current value will be called url
for url in urls: # Here url is the value inside the list
htmlfile = urllib.urlopen(url)
htmltext = htmlfile.read()
print htmltext
使用for循环的演示:
>>> for url in urls:
print url
hello
world
>>>
我是否还建议您使用python-requests, 它非常适合通过常见的 HTTP 协议(例如GET和)发送请求POST。以后会省去很多麻烦。