如何将这些标题添加到我的python urllib开启工具?

时间:2013-03-16 22:32:08

标签: python http url urllib2

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

3 个答案:

答案 0 :(得分:5)

你的开场白应该有一个属性addheaders,这是一个元组列表。默认情况下,它包含用户代理。

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

答案 1 :(得分:2)

这样的事情可能有用:

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

答案 2 :(得分:1)

你应该先把字典转换成元组。

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