Simple URL GET/POST function in Python

前端 未结 5 1656
旧时难觅i
旧时难觅i 2020-11-28 18:52

I can\'t seem to Google it, but I want a function that does this:

Accept 3 arguments (or more, whatever):

  • URL
  • a dictionary of params
5条回答
  •  臣服心动
    2020-11-28 19:30

    import urllib
    
    def fetch_thing(url, params, method):
        params = urllib.urlencode(params)
        if method=='POST':
            f = urllib.urlopen(url, params)
        else:
            f = urllib.urlopen(url+'?'+params)
        return (f.read(), f.code)
    
    
    content, response_code = fetch_thing(
                                  'http://google.com/', 
                                  {'spam': 1, 'eggs': 2, 'bacon': 0}, 
                                  'GET'
                             )
    

    [Update]

    Some of these answers are old. Today I would use the requests module like the answer by robaple.

提交回复
热议问题