Accept Cookies in Python

后端 未结 6 625
孤城傲影
孤城傲影 2020-12-31 11:43

How can I accept cookies in a python script?

相关标签:
6条回答
  • 2020-12-31 12:14

    The easiest way is to use requests library.

    import requests
    url = 'http://www.google.com/doodles/'
    r = requests.get(url)
    print r.cookies
    
    0 讨论(0)
  • 2020-12-31 12:17

    I believe you mean having a Python script that tries to speak HTTP. I suggest you to use a high-level library that handles cookies automatically. pycurl, mechanize, twill - you choose.

    For Nikhil Chelliah:

    I don't see what's not clear here.

    Accepting a cookie happens client-side. The server can set a cookie.

    0 讨论(0)
  • 2020-12-31 12:18

    It's unclear whether you want a client-side or a server-side solution.

    For client-side, cookielib will work fine. This answer and a few web tutorials offer more in-depth explanations.

    If this is a server-side problem, you should be using a framework that takes care of all the boilerplate. I really like how CherryPy and web.py handle them, but the API is pretty simple in any library.

    0 讨论(0)
  • 2020-12-31 12:25

    You might want to look at cookielib.

    0 讨论(0)
  • 2020-12-31 12:30

    Try this:

    import urllib2 
    import cookielib
    
    jar = cookielib.FileCookieJar("cookies")
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
    
    print "Currently have %d cookies" % len(jar)
    print "Getting page"
    response = opener.open("http://google.com")
    print response.headers
    print "Got page"
    print "Currently have %d cookies" % len(jar)
    print jar
    

    It should print

    Currently have 0 cookies
    ...
    Currently have 2 cookies
    

    (Google always sets a cookie). You don't really need this much unless you want to save your cookies to disk and use them later. You should find that

    urllib2.build_opener(HTTPCookieProcessor).open(url)
    

    Takes care of most of what you want.

    More info here:

    • HTTPCookieProcessor
    • build_opener
    • FileCookieJar
    • Urllib2 - the missing maual
    0 讨论(0)
  • 2020-12-31 12:35

    There's the cookielib library. You can also implement your own cookie storage and policies, the cookies are found in the set-cookie header of the response (Set-Cookie: name=value), then you send the back to a server in one or more Cookie headers in the request (Cookie: name=value).

    0 讨论(0)
提交回复
热议问题