7

I tries to use Requests library in python for crawling, I first imported the requests module,and then I use get function to call the website for getting a response named r, but I can not understand why the type of r is class,could you please tell me why ,thank you very much.

I also want to check the request header, I checked some documents, it says that I can use r.request.headers, what does the request here mean, is it a method?

>>> import requests
>>> r=requests.get("http://www.baidu.com")
>>> type(r)
<class 'requests.models.Response'>
8
  • this is simply a class....follow this link to het idea about how to use get...stackoverflow.com/questions/27803503/…
    – Amrit
    Commented Nov 9, 2017 at 4:10
  • 1
    check the output of help(r) . You'll get a clear picture of what is the base class, from where it is inherited from and few definitions! Commented Nov 9, 2017 at 4:10
  • That's just how the class is represented.
    – jhpratt
    Commented Nov 9, 2017 at 4:10
  • The response is an object derived from class requests.models.Response, makes sense, no?
    – Nir Alfasi
    Commented Nov 9, 2017 at 4:12
  • @alfasin, the response is an object or instance here ?
    – jing
    Commented Nov 9, 2017 at 4:50

4 Answers 4

13

You're getting a Response object after you fire off the request. To get data from the response object you need to access the property you're after, e.g. r.status_code, r.text, etc.

See this documentation for more details.

3
  • Hi,Jerry, does the object here mean instance or just class object ?
    – jing
    Commented Nov 9, 2017 at 4:49
  • @jing Instance of a class.
    – Jerry
    Commented Nov 9, 2017 at 22:45
  • Documentation link is broken Commented Nov 2, 2020 at 20:01
5

For the <class 'requests.models.Response'> has following attributes:

['_content', '_content_consumed', '_next', 'status_code', 'headers', 'raw', 'url', 'encoding', 'history', 'reason', 'cookies', 'elapsed', 'request', 'connection', '__module__', '__doc__', '__attrs__', '__init__', '__enter__', '__exit__', '__getstate__', '__setstate__', '__repr__', '__bool__', '__nonzero__', '__iter__', 'ok', 'is_redirect', 'is_permanent_redirect', 'next', 'apparent_encoding', 'iter_content', 'iter_lines', 'content', 'text', 'json', 'links', 'raise_for_status', 'close', '__dict__', '__weakref__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
1

It is response from HTTP request. If this is a REST API that you are making a call to, you can convert the response to JSON by calling r.json().

1
-1

Its just a response to the request you're sending, hope this helps :)

Not the answer you're looking for? Browse other questions tagged or ask your own question.