在我用浏览器打开URL之前,程序不会让我做任何事情!

选择 | 换行 | 行号
  1. import urllib
  2. from urllib2 import urlopen
  3. from gzip import GzipFile
  4. from cStringIO import StringIO
  5. import re
  6. import urllib2
  7.  
  8. def download(url):
  9.     s = urlopen(url).read()
  10.     if s[:2] == '\x1f\x8b': # assume it's gzipped data
  11.         with GzipFile(mode='rb', fileobj=StringIO(s)) as ifh:
  12.             s = ifh.read()
  13.     return s
  14.  
  15. s = download('http://www.locationary.com/place/en/US/Virginia/Richmond-page20/?ACTION_TOKEN=NumericAction')
  16.  
  17. findLoc = re.compile('http://www\.locationary\.com/place/en/US/Virginia/Richmond/.{1,100}\.jsp')
  18.  
  19. findLocL = re.findall(findLoc,s)
  20.  
  21. for i in range(0,25):
  22.  
  23.     def download(url):
  24.         s = urlopen(url).read()
  25.         if s[:2] == '\x1f\x8b': # assume it's gzipped data
  26.             with GzipFile(mode='rb', fileobj=StringIO(s)) as ifh:
  27.                 s = ifh.read()
  28.         return s
  29.  
  30.     b = download(findLocL[i])
  31.  
  32.     findYP = re.compile('http://www\.yellowpages\.com/.{1,100}\d{1,100}')
  33.  
  34.     findYPL = re.findall(findYP,b)
  35.  
  36.     for c in range(1):
  37.  
  38.         print findYPL[c]
  39.  

这就是它给我的错误:
回溯(最近一次呼叫):
文件"C:\Users\Robert\Documents\j-a-c-o-b\locationary.py",第65行,在
打印findYPL[c]
IndexError:列表索引超出范围
然而,当我打开Google Chrome并打开所有链接(在程序中称为("findLocL[i]"或"b"),然后运行该程序时,它就工作了……
为什么会发生这种事?

# 回答1



顺便说一句,您不需要两次定义下载。
如果您将第36行更改为:

选择 | 换行 | 行号
  1. for c in range(len(findYPL)):

或者可能是这样的:

选择 | 换行 | 行号
  1. for c in range(min([len(findYPL),1])):

也许会更好:

选择 | 换行 | 行号
  1. for c in findYPL:
  2.     print c

这可能会有帮助。当然,我不知道你到底想要达到什么目的,所以如果你提供一些背景知识,我们或许能帮到你。论坛一般都是这样的。我们不是读心术。

标签: python

添加新评论