Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop though list properly?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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/
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading