Q:

Mechanize random User-Agent

I'm trying to get Mechanize to use a random User-Agent every time I initiate opening a URL.
Can someone point me in the right direction that I need to take in order to do this? - I've searched everywhere and couldn't find a reference.
Thanks!

A:

I had the same problem when I was doing web crawlers, and this is the solution that I used:
class URLOpener():      
    def opener(self,user_agent):
        cj=cookielib.CookieJar()
        #Process Hadlers
        opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        opener.addheaders=[
                        ('User-Agent', user_agent),
                        ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
                        ('Accept-Language', 'en-gb,en;q=0.5'),
                        ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'),
                        ('Keep-Alive', '115'),
                        ('Connection', 'keep-alive'),
                        ('Cache-Control', 'max-age=0'),
                    ]
        return opener

    #Openers with different User-Agents
    def opener_list(self,f_path):
        #f_path is a path to the file that contains browsers
        f=open(f_path, 'r+')
        count=0
        user_agent_list=list()
        for line in f.xreadlines():
            count+=1
            user_agent_list.append(line[:-1])
        openers=[self.opener(user_agent) for user_agent in user_agent_list]
        return openers

also file that I created looked similar to that:
Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
Mozilla/5.0 (Linux; U; Android 4.0.3; de-ch; HTC Sensation Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
Mozilla/5.0 (Linux; U; Android 2.3; en-us) AppleWebKit/999+ (KHTML, like Gecko) Safari/999.9
Mozilla/5.0 (Linux; U; Android 2.3.5; zh-cn; HTC_IncredibleS_S710e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
Mozilla/5.0 (Linux; U; Android 2.3.5; en-us; HTC Vision Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
Mozilla/5.0 (Linux; U; Android 2.3.4; fr-fr; HTC Desire Build/GRJ22) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; T-Mobile myTouch 3G Slide Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
Mozilla/5.0 (Linux; U; Android 2.3.3; zh-tw; HTC_Pyramid Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
Mozilla/5.0 (Linux; U; Android 2.3.3; zh-tw; HTC_Pyramid Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari
Mozilla/5.0 (Linux; U; Android 2.3.3; zh-tw; HTC Pyramid Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

