Sometimes, we want to use Python requests to fake a browser visit with a generated user agent.
In this article, we’ll look at how to use Python requests to fake a browser visit with a generated user agent.
How to use Python requests to fake a browser visit with a generated user agent?
To use Python requests to fake a browser visit with a generated user agent,, we can use the fake_useragent library.
To install it, we run
pip install fake-useragent
Then we use it by writing
from fake_useragent import UserAgent
import requests
ua = UserAgent()
header = {"User-Agent": str(ua.chrome)}
url = "https://www.example.com"
html_content = requests.get(url, headers=header)
print(html_content)
We create the UserAgent object with
ua = UserAgent()
Then we get the user agent string we want from the ua object.
Next, we call requests.get to make a request to the url with the headers.
The headers is a dict with the value of the User-Agent request header.
Conclusion
To use Python requests to fake a browser visit with a generated user agent,, we can use the fake_useragent library.