2013-10-13 125 views
0

我使用计算器this后的代码unshorten网址...无法解开bit.ly网址?

import httplib 
import urlparse 

def unshorten_url(url): 
    parsed = urlparse.urlparse(url) 
    h = httplib.HTTPConnection(parsed.netloc) 
    resource = parsed.path 
    if parsed.query != "": 
     resource += "?" + parsed.query 
    h.request('HEAD', resource) 
    response = h.getresponse() 
    if response.status/100 == 3 and response.getheader('Location'): 
     return unshorten_url(response.getheader('Location')) # changed to process chains of short urls 
    else: 
     return url 

所有缩短链接bit.ly的新创建的URL unshortned“CEPT。

我得到这个错误:

>>> unshorten_url("bit.ly/1atTViN") 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 7, in unshorten_url 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 955, in request 
    self._send_request(method, url, body, headers) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 989, in _send_request 
    self.endheaders(body) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 951, in endheaders 
    self._send_output(message_body) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 811, in _send_output 
    self.send(msg) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 773, in send 
    self.connect() 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 754, in connect 
    self.timeout, self.source_address) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 571, in create_connection 
    raise err 
socket.error: [Errno 61] Connection refused 

是怎么回事?

+0

downvote最初发布的答案,收到6 upvotes – sirvon

+0

@ user2799617:然后downvote原来的,而不是这个问题。 –

+0

http://www.ankitpanda.com/tweeting-with-python/,但我已经尝试过另一个网址以及... youtube.com/watch?v=eeAjkbNq4xI – sirvon

回答

3

你忘了包括URL方案:

unshorten_url("http://bit.ly/1atTViN") 

注意http://那里,那是重要。没有它,网址是不正确解析:

>>> import urlparse 
>>> urlparse.urlparse('bit.ly/1atTViN') 
ParseResult(scheme='', netloc='', path='bit.ly/1atTViN', params='', query='', fragment='') 
>>> urlparse.urlparse('http://bit.ly/1atTViN') 
ParseResult(scheme='http', netloc='bit.ly', path='/1atTViN', params='', query='', fragment='') 

查看如何当不包括http://netloc参数为空;你最终试图连接到你自己的机器,而你没有运行网络服务器,因此连接被拒绝。

+0

哇!非常感谢你。非常有意义。 – sirvon

0

可能bit.ly拒绝来自httplib等工具的连接。你可以尝试改变用户代理是这样的:

h.putheader('User-Agent','Mozilla/5.0 (X11; U; Linux i686; pl-PL; rv:1.7.10) Gecko/20050717 Firefox/1.0.6') 
+1

连接在发送*头之前被拒绝*。 –