urllib2 with cookies

前端 未结 2 2004
暗喜
暗喜 2021-01-05 15:35

I am trying to make a request to an RSS feed that requires a cookie, using python. I thought using urllib2 and adding the appropriate heading would be sufficient, but the re

相关标签:
2条回答
  • 2021-01-05 15:57
    import urllib2
    opener = urllib2.build_opener()
    opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
    f = opener.open("http://example.com/")
    
    0 讨论(0)
  • 2021-01-05 16:02

    I would use requests package, docs, it's a lot easier to use than urlib2 (sane API).

    If a response contains some Cookies, you can get quick access to them:

    url = 'http://httpbin.org/cookies/set/requests-is/awesome'
    r = requests.get(url)
    print r.cookies #{'requests-is': 'awesome'}
    

    To send your own cookies to the server, you can use the cookies parameter:

    url = 'http://httpbin.org/cookies'
    cookies = dict(cookies_are='working')
    r = requests.get(url, cookies=cookies)
    r.content # '{"cookies": {"cookies_are": "working"}}'
    

    http://docs.python-requests.org/en/latest/user/quickstart/#cookies

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