-
Notifications
You must be signed in to change notification settings - Fork 44
/
ua.py
61 lines (50 loc) · 1.48 KB
/
ua.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#coding:utf-8
import codecs
import json
import random
from config import HEADER
class RandomHeader:
def __init__(self):
self.ua = UserAgent()
self.header = HEADER
def Header(self, referer=''):
header = self.header
header['User-Agent'] = self.ua.random
if referer:
header['Referer'] = referer
return header
class UserAgent(object):
def __init__(self):
self.data = self.load('ua.json')
self.SHORTCUTS = {
'ie': 'internetexplorer',
}
def load(self, db):
with codecs.open(db, encoding='utf-8', mode='rb',) as fp:
return json.load(fp)
def __getitem__(self, attr):
return self.__getattr__(attr)
def __getattr__(self, attr):
attr = attr.lower()
if attr == 'random':
attr = self.data['randomize'][
str(random.randint(0, len(self.data['randomize']) - 1))
]
else:
if attr in self.SHORTCUTS:
attr = self.SHORTCUTS[attr]
try:
return self.data['browsers'][attr][
random.randint(
0, len(self.data['browsers'][attr]) - 1
)
]
except KeyError:
return None
if __name__ == '__main__':
ua = UserAgent()
print ua['opera']
print ua['ie']
print ua.chrome
print ua.firefox
print ua.random