【问题标题】:How do I fetch url with urllib2 without declaring a url scheme?如何在不声明 url 方案的情况下使用 urllib2 获取 url?
【发布时间】:2013-03-10 05:48:04
【问题描述】:

这可能是一个愚蠢的问题,但我可以在不声明 http 或 https 之类的 url 方案的情况下使用 urllib2 获取 url

为了澄清而不是写'http://blahblah.com',我只想写'blahblah.com',这可能吗?

【问题讨论】:

  • 如果只是 http 或 https,您可以将其添加为前缀..
  • 没有方案,你怎么知道使用什么协议或端口?实际上有数百种协议可以使用——仅仅一个主机名并不足以告诉一个愚蠢的系统选择什么协议。

标签: python http url urllib2


【解决方案1】:
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”的 URL,此函数仍然会失败,因为它假定如果没有方案,则没有前导双正斜杠。

【讨论】:

    猜你喜欢
    • 2010-10-15
    • 2012-04-19
    • 2019-09-26
    • 2020-09-09
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 2016-02-03
    相关资源
    最近更新 更多