Python Mechanize - how to add a header on a single .open() call?

瘦欲@ 提交于 2019-12-01 06:42:33

Do it like this:

import mechanize
import urllib2

browser = mechanize.Browser()

# setup your header, add anything you want
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1', 'Referer': 'http://whateveritis.com'}
url = "http://google.com"

# wrap the request. You can replace None with the needed data if it's a POST request
request = urllib2.Request(url, None, header)

# here you go
response = browser.open(request)

print response.geturl()
print response.read()
response.close()

You could make use of the python with statement. Make a class like this:

class ExtraHeaders(object):
    def __init__(self, br, headers):
        self.extra_headers = headers
        self.br = br
    def __enter__(self):
        self.old_headers = self.br.addheaders
        self.br.addheaders = self.extra_headers + [h for h in self.br.addheaders if 
            not reduce(
                lambda accum, ex_h: accum or ex_h[0] == h[0],self.extra_headers,False)]
        return self.br
    def __exit__(self, type, value, traceback):
        self.br.addheaders = self.old_headers

Then use it this way:

with ExtraHeaders(browser, [AJAX_HEADER]):
    browser.open('/admin/discounts', urllib.urlencode(pulled_params))
#requests beyond this point won't have AJAX_HEADER

Note that if you're multithreading, any threads accessing the browser while another thread is inside the with statement will have the extra headers too.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!