TIMEX
TIMEX

Reputation: 271694

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)?

Upvotes: 3

Views: 9126

Answers (3)

Trinidad
Trinidad

Reputation: 231

You should turn the dict to the tuple first.

opener.addHeaders=tuple(items for items in headers.items())

Upvotes: 1

Vor
Vor

Reputation: 35109

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

Upvotes: 3

t-8ch
t-8ch

Reputation: 2713

Your opener should have an attribute addheaders, which is a list of tuples. By default it contains the user agent.

opener.addheaders.append(('Host', 'www.namestation.com'))

Upvotes: 6

Related Questions