【问题标题】:Python: urllib2.HTTPError: HTTP Error 300: Multiple ChoicesPython:urllib2.HTTPError:HTTP 错误 300:多项选择
【发布时间】:2015-12-15 00:05:04
【问题描述】:

我有一个脚本,它在网页文本页面中查找信息,然后将它们存储在字典中。 该脚本正在列表中查找 URL,然后在循环中处理它们,但是它在处理过程中被此错误中断:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 406, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 444, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 300: Multiple Choices

我无法解释这一点,我不知道是否有办法避免此类问题。 有没有办法在脚本中添加异常?

这是我的脚本:

import urllib2
import sys
import re

IDlist = ['C9JVZ1', 'C9JLN0', 'C9J872']  #(there is more than 1500 of them)

URLlist = ["http://www.uniprot.org/uniprot/"+x+".txt" for x in IDlist]

function_list = {}
for id, item in zip(IDlist, URLlist):
    function_list[id] = []
    textfile = urllib2.urlopen(item);
    myfile = textfile.readlines();
    for line in myfile:
        print "line:", line;
        found = re.search('\s[C]:(.+?);', line);
        if found:
            function = found.group(1);
            function_list[id].append(function)

【问题讨论】:

    标签: python web urllib2 http-error


    【解决方案1】:

    Web 服务器正在为您要访问的 URL 之一返回 HTTP 状态代码 300 Multiple Choices(请参阅Wikipedia)。这可能意味着您列表中的某个 URL 有误,而 Web 服务器希望通过提供类似现有 URL 的列表来帮助您。

    一般而言,urllib2 会将任何不成功或简单的重定向响应转换为异常,这就是您在那里看到的。

    当您不在某处处理异常时,例如带有try-except 块通常会终止您的程序。因此,您需要将您对 urlopen 的调用包装在 try 块中:

    try:
      textfile = urllib2.urlopen(item);
    except urllib2.HTTPError:
      # Do something here to handle the error. For example:
      print("URL", item, "could not be read.")
      continue
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      相关资源
      最近更新 更多