Skip to content

Commit

Permalink
[NEW] add ability to choose random useragent
Browse files Browse the repository at this point in the history
  • Loading branch information
sottom committed May 20, 2020
1 parent edef769 commit 4e2e401
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions riko/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import sys
import itertools as it
import fcntl
import random
from riko import __version__

from math import isnan
Expand Down Expand Up @@ -71,14 +72,49 @@ def make_blocking(f):
make_blocking(sys.stderr)


def default_user_agent(name="riko"):
def random_useragent():
return random.choice([
("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"),
("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36"),
("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) "
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15"),
("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"),
("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"),
("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) "
"Gecko/20100101 Firefox/75.0"),
("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"),
("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36"),
("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"),
("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) "
"Gecko/20100101 Firefox/76.0"),
("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36"),
("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) "
"Gecko/20100101 Firefox/75.0"),
("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:75.0) "
"Gecko/20100101 Firefox/75.0"),
])


def default_useragent(name="riko"):
"""
Return a string representing the default user agent.
:rtype: str
"""
return '%s/%s' % (name, __version__)


def get_useragent(random=False):
return random_useragent() if random else default_useragent()


class Chainable(object):
def __init__(self, data, method=None):
self.data = data
Expand Down Expand Up @@ -209,7 +245,7 @@ def open(self, url, **params):
r.raw.decode_content = self.decode
response = r.text if self.cache_type else r.raw
else:
req = Request(url, headers={'User-Agent': default_user_agent()})
req = Request(url, headers={'User-Agent': get_useragent()})
try:
r = urlopen(req, context=self.context, timeout=self.timeout)
except TypeError:
Expand Down

0 comments on commit 4e2e401

Please sign in to comment.