What is the quickest way to HTTP GET in Python?

What is the quickest way to HTTP GET in Python if I know the content will be a string? I am searching the docs for a quick one-liner like:

contents = url.get("http://example.com/foo/bar")

But all I can find using Google are httplib and urllib - and I am unable to find a shortcut in those libraries.

Does standard Python 2.5 have a shortcut in some form as above, or should I write a function url_get ?

  • I would prefer not to capture the output of shelling out to wget or curl .

  • Python 2.x:

    import urllib2
    contents = urllib2.urlopen("http://example.com/foo/bar").read()
    

    Python 3.x:

    import urllib.request
    contents = urllib.request.urlopen("http://example.com/foo/bar").read()
    

    Documentation for urllib.request and read.

    How is that?


    You could use a library called requests.

    import requests
    r = requests.get("http://example.com/foo/bar")
    

    This is quite easy. Then you can do like this:

    >>> print r.status_code
    >>> print r.headers
    >>> print r.content
    

    如果你想用httplib2解决问题,请考虑instatntinating匿名Http对象

    import httplib2
    resp, content = httplib2.Http().request("http://example.com/foo/bar")
    
    链接地址: http://www.djcxy.com/p/17582.html

    上一篇: HTTP GET请求的最大长度?

    下一篇: 在Python中使用HTTP GET最快的方法是什么?