Question

I would prefer to only use urllib2 and urllib for this and I know the question has already been answered on here, but when I was reading through responses I got incredibly confused. A lot of the responses recommended using things that included the word "header" so are cookies just a regular headers like http://myhttp.info/, or are they a subset? I am also confused on how I could successfully implement them into the my code

def getURLSourceFromChrome(url):
    values = {}
    headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36',
                'connection' : 'keep-alive',
                'Accept' :     'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Referer' : 'http://google.com/',
                }

    data = urllib.urlencode(values)
    req = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(req)
    return response.read()

Most of the responces used urllib.buildopener() and I am wondering if I have to use that method to accomplish the task or if I could simply add it to my code like so:

def getURLSourceFromChrome(url):
    values = {}
    headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36',
                'connection' : 'keep-alive',
                'Accept' :     'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Referer' : 'http://google.com/',
                'someCookie' : 'SomeCookieInformation'
                }

    data = urllib.urlencode(values)
    req = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(req)
    return response.read()

I am using Python 2.7

Was it helpful?

Solution

"to set multiple cookie add set-cookie header as many times as you need. About quotation marks, in python should be header = {... "Set-Cookie":"name=vale" ...} if your question is about http specification of Set-Cookie see link – ejrav"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top