2013-03-20 59 views
1

这可能是一个愚蠢的问题,但我可以取得与urllib2的一个网址,不宣而像HTTP或HTTPS如何在不声明url方案的情况下使用urllib2获取url?

的URL方案澄清,而不是写“http://blahblah.com”我只想写“blahblah.com”,这是可能吗?

+0

如果它只是http或https,那么您可以将其添加为前缀。 – Kartik 2013-03-20 21:43:30

+1

如果没有该方案,您将如何知道要使用哪种协议或端口?实际上有数百个协议可以使用 - 只是一个主机名不足以告诉愚蠢的系统选择什么协议。 – Kylar 2013-03-21 01:07:59

回答

0
import urllib2 

def open_url_with_default_protocol(*args, **kwargs): 
    # Use the HTTP scheme by default if none is given 
    # pass through all other arguments to urllib2.urlopen 

    default_scheme = 'http://' 

    url = args[0] 
    scheme, address = urllib2.splittype(url) 

    if not scheme: 
     # Replace the url in the args tuple by a URL with the default scheme 
     args = (default_scheme + args[0],) + args[1:] 

    return urllib2.urlopen(*args, **kwargs) 

所以,你可以这样做:

>>> open_url_with_default_protocol('http://google.com') 
<addinfourl at 4496800872 whose fp = <socket._fileobject object at 0x10bd92b50>> 
>>> open_url_with_default_protocol('google.com') 
<addinfourl at 4331750464 whose fp = <socket._fileobject object at 0x1027960d0>> 

请注意,该功能仍然会失败,如果你通过它的形式“//google.com”的网址,因为它假设,如果有没有计划,没有领先的双向前锋。

相关问题