urllib2 为 url 抛出错误,而它在浏览器中正确打开 [英] urllib2 is throwing an error for an url , while it's opening properly in browser

查看:18
本文介绍了urllib2 为 url 抛出错误,而它在浏览器中正确打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试像这样通过python打开一个网址

I am trying to open an url through python like this

  import urllib2
  f = urllib2.urlopen('http://www.futurebazaar.com/Search/laptop')

它抛出以下错误

文件C:\Python26\lib\urllib2.py",第 1134 行,在 do_open 中r = h.getresponse() 文件C:\Python26\lib\httplib.py",行986,在得到响应response.begin() 文件C:\Python26\lib\httplib.py",行391,在开始版本、状态、原因 = self._read_status() 文件"C:\Python26\lib\httplib.py", 行355,在_read_status引发 BadStatusLine(line) httplib.BadStatusLine

File "C:\Python26\lib\urllib2.py", line 1134, in do_open r = h.getresponse() File "C:\Python26\lib\httplib.py", line 986, in getresponse response.begin() File "C:\Python26\lib\httplib.py", line 391, in begin version, status, reason = self._read_status() File "C:\Python26\lib\httplib.py", line 355, in _read_status raise BadStatusLine(line) httplib.BadStatusLine

但是这个网址是通过浏览器打开的.

But this url is opening via browser.

推荐答案

网站坏了.如果未提供可选的接受"标头,站点将关闭连接而不响应;这是无效行为.

The website is broken. If the optional "Accept" header isn't supplied, the site closes the connection without responding; this is invalid behavior.

解决方法:

import urllib2
req = urllib2.Request('http://www.futurebazaar.com/Search/laptop')
req.add_header('Accept', '*/*')
f = urllib2.urlopen(req)

这篇关于urllib2 为 url 抛出错误,而它在浏览器中正确打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆