我的代码如下,但运行时会抛出错误。
search_request = urllib2.Request(url,data=tmp_file_name,headers={'X-Requested-With':'WoMenShi888XMLHttpRequestWin'})
#print search_request.get_method()
search_response = urllib2.urlopen(search_request)
html_data = search_response.read()
错误是:
Traceback (most recent call last):
File "xx_tmp.py", line 83, in <module>
print hello_lfi()
File "xx_tmp.py", line 69, in hello_lfi
search_response = urllib2.urlopen(search_request)
File "D:\Python27\lib\urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "D:\Python27\lib\urllib2.py", line 406, in open
response = meth(req, response)
File "D:\Python27\lib\urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "D:\Python27\lib\urllib2.py", line 444, in error
return self._call_chain(*args)
File "D:\Python27\lib\urllib2.py", line 378, in _call_chain
result = func(*args)
File "D:\Python27\lib\urllib2.py", line 527, in http_error_defau
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 500: Internal Server Error
不知道怎么解决?我的意思是,当发生错误时,我的代码如何继续工作?
当我尝试使用时
try:
search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
pass
新错误
UnboundLocalError: local variable 'search_response' referenced before assignment
我用
global search_response
并且有错误
NameError: global name 'search_response' is not defined
最佳答案
您可以捕获异常,这将防止您的程序“突然”停止:
try:
search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
print 'There was an error with the request'
如果您想继续,您可以简单地:
try:
search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
pass
这将使您的程序能够继续;但您的其他语句 html_data = search_response.read()
不会给您预期的结果。要永久解决此问题,您需要调试您的请求以查看失败的原因;这不是 Python 特有的东西。
关于python - 当我使用 urllib2 时回溯,收到 HTTP 500 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14020784/