Search code examples
pythonhttpurlurllib2

How do I add these headers to my python urllib opener?


headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'X-Requested-With': 'XMLHttpRequest',
    'Referer': 'http://www.namestation.com/domain-search?autosearch=1',
    'Origin': 'http://www.namestation.com',
    'Host': 'www.namestation.com',
    'Content-Type': 'application/json; charset=UTF-8',
    'Connection': 'keep-alive'
}
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

opener.addHeaders(headers)?


Solution

  • Something like this may work:

    def opener():
        cj=cookielib.CookieJar()
        #Process Hadlers
        opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        opener.addheaders=[
                        ('Accept', 'application/json, text/javascript, */*; q=0.01'),
                        ('X-Requested-With', 'XMLHttpRequest'),
                        ('Referer', 'http://www.namestation.com/domain-search?autosearch=1'),
                        ('Host', 'www.namestation.com'),
                        ('Content-Type', 'application/json; charset=UTF-8'),
                        ('Connection', 'keep-alive'),
                    ]
        return opener