Accept Cookies in Python

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

How can I accept cookies in a python script?

6条回答
  •  野趣味
    野趣味 (楼主)
    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

提交回复
热议问题