fake_useragent
package can randomly generate user agents:
from fake_useragent import UserAgent
ua = UserAgent()
user_agent = ua.random
Sometimes generated user agents have outdated browser versions and some websites don‘t accept them. Is there any way to generate user agents only with the latest browser versions?
Yes, when a browser or any client sends a different user-agent HTTP header from what they are and fake it that is called spoofing. While the term may be alarming, this is not a dangerous activity and will not cause any problems for you. (So feel free to spoof your user-agent as much as you want.
Just right click on any page and select your user-agent. This Chrome extension adds a toolbar button and a menu to switch between user-agents. Browse with our predefined user-agents or add your own user-agents. Changing User-Agent allows you to mimic, spoof or fake other browsers, devices or search engine spiders.
The user-agent string of the browser is accessed using the navigator. userAgent property and then stored in a variable. The presence of the strings of a browser in this user-agent string is detected one by one. Detecting the Chrome browser: The user-agent of the Chrome browser is “Chrome”.
To override the user agent string from Microsoft Edge DevTools: Press Ctrl + Shift + P (Windows, Linux) or Command + Shift + P (macOS) to open the Command Menu. Type network conditions , select Show Network conditions, and then press Enter to open the Network conditions tool.
You could do the following:
from fake_useragent import UserAgent
import random
import re
def grp(pat, txt):
r = re.search(pat, txt)
return r.group(0) if r else '&'
ua = UserAgent()
browsers = {
'chrome': r'Chrome/[^ ]+',
'safari': r'AppleWebKit/[^ ]+',
'opera': r'Opera\s.+$',
'firefox': r'Firefox/.+$',
'internetexplorer': r'Trident/[^;]+',
}
for k, v in browsers.items():
print(sorted(ua.data_browsers[k], key=lambda a: grp(v, a))[-1])
The output of the script is:
Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A
Opera/9.80 (Windows NT 6.1; Opera Tablet/15165; U; en) Presto/2.8.149 Version/11.1
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1
Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko
Please note that the grp
function was blatantly stolen from this answer
If you instead are only looking for a single browser, like you asked, this would choose randomly while honoring the probabilities as lined out in the project's readme
browser = random.choice(ua.data_randomize)
print(sorted(ua.data_browsers[browser], key=lambda a: grp(browsers[browser], a))[-1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With