Requests.get in Python using a "User-Agent" not mimicking a browser request

I need to collect information from web pages using Python from a Linux terminal, it works fine, but some pages (not all of them) get the wrong URL when I try to use request.get because they have agent detectors, and they don’t know how to answer my request (I’m not a browser or mobile application from a Linux terminal).

Using the "User-Agent" header didn’t work either, I tried several different ways to send it for emulation. I am a Mozilla browser:

user_agent = {'User-Agent': 'Mozilla/5.0'}

or

user_agent = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; hu-HU; rv:1.7.8) Gecko/20050511 Firefox/1.0.4'}

or many other combinations.

On some servers, when I try to use this line:

page = requests.get(url, headers=user_agent)

, - , .

- , User-Agent ? Python Notebook, - , () .

+4
2

, , - .

>>> import requests
>>> header = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0',}
>>> url = 'http://www.w3.org/'
>>> r = requests.get(url, headers=header)
>>> r.headers
CaseInsensitiveDict({'content-length': '40737', 'content-location': 'Home.html', 'accept-ranges': 'bytes', 'expires': 'Tue, 24 Jun 2014 04:44:36 GMT', 'vary': 'negotiate,accept', 'server': 'Apache/2', 'tcn': 'choice', 'last-modified': 'Mon, 23 Jun 2014 11:15:15 GMT', 'etag': '"9f21-4fc7ef51956c0;89-3f26bd17a2f00"', 'cache-control': 'max-age=600', 'date': 'Tue, 24 Jun 2014 04:34:36 GMT', 'p3p': 'policyref="http://www.w3.org/2001/05/P3P/p3p.xml"', 'content-type': 'text/html; charset=utf-8'})
>>> r.request.headers
CaseInsensitiveDict({'Accept-Encoding': 'gzip, deflate, compress', 'Accept': '*/*', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0'})
>>> 
+8

UserAgent

:

from fake_useragent import UserAgent
import requests


ua = UserAgent()
print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
print(header)
url = "https://www.hybrid-analysis.com/recent-submissions?filter=file&sort=^timestamp"
htmlContent = requests.get(url, headers=header)
print(htmlContent)

:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17
{'User-Agent': 'Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'}
<Response [200]>
+2

Source: https://habr.com/ru/post/1542091/


All Articles