Home > OS >  How to loop though list properly?
How to loop though list properly?

Time:06-29

Here is a simple list I am trying to loop but it throws error AttributeError: 'Response' object has no attribute 'i' whats wrong here kindly suggest

response = requests.get(url)
m1 = ['ok', 'raise_for_status', 'raw', 'reason',
      'request', 'status_code', 'text', 'url']

for i in m1:
    print(i)
    print(response.i)

Expected example is like reponse.url returns the url used

It works if tried individually

CodePudding user response:

The way to loop through those attributes is the following.

Code

import requests

response = requests.get('http://example.com')
m1 = ['ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']

for i in m1:
    print(i)
    print(getattr(response, i))

Output

ok
True
raise_for_status
<bound method Response.raise_for_status of <Response [200]>>
raw
<urllib3.response.HTTPResponse object at 0x10433b7c0>
reason
OK
request
<PreparedRequest [GET]>
status_code
200
text
<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        
    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 2em;
        background-color: #fdfdff;
        border-radius: 0.5em;
        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        div {
            margin: 0 auto;
            width: auto;
        }
    }
    </style>    
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>

url
http://example.com/
  • Related