为什么这个请求不起作用?
我想用Twitter的API做一个简单的Twitter应用。
如果我在浏览器里请求这个页面,它是可以正常工作的:
http://search.twitter.com/search.atom?q=hello&rpp=10&page=1
但是如果我用Python的urllib或urllib2来请求这个页面,大多数时候就不行:
response = urllib2.urlopen("http://search.twitter.com/search.atom?q=hello&rpp=10&page=1")
然后我就会收到这个错误:
Traceback (most recent call last):
File "twitter.py", line 24, in <module>
response = urllib2.urlopen("http://search.twitter.com/search.atom?q=hello&rpp=10&page=1")
File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.6/urllib2.py", line 391, in open
response = self._open(req, data)
File "/usr/lib/python2.6/urllib2.py", line 409, in _open
'_open', req)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 1161, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.6/urllib2.py", line 1136, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 110] Connection timed out>
这是为什么呢??
2 个回答
1
你有没有在你的代码里改过默认的socket超时时间?我这段示例代码运行得很稳定。
可能是你的网络连接有问题,或者你可以试试
import socket
socket.setdefaulttimeout(30)
假设urllib/2没有覆盖socket的超时时间。
2
这段代码看起来没问题。
下面的代码可以正常运行。
>>> import urllib
>>> import urllib2
>>> user_agent = 'curl/7.21.1 (x86_64-apple-darwin10.4.0) libcurl/7.21.1'
>>> url='http://search.twitter.com/search.atom?q=hello&rpp=10&page=1'
>>> headers = { 'User-Agent' : user_agent }
>>> req = urllib2.Request(url, None, headers)
>>> response = urllib2.urlopen(req)
>>> the_page = response.read()
>>> print the_page
另外,Twitter 实际上无法响应。这种情况发生得太频繁了。