簡體   English   中英

將for循環中的多個打印output值存儲到列表或變量中

[英]Store multiple print output values from for loop into a list or variable

我進入 python 和 pandas 幾天,我遇到了我自己似乎無法解決的情況。 我有一個 for 循環來獲取狀態代碼並在它們滿足某些條件時打印出結果。 我的for循環如下:

對於循環:

import requests
from requests.exceptions import HTTPError

response_full_result = []

for url in url_list:
    try:
       response = requests.get(url)
       response_full_result.append(response)

       # If the response was successful, no Exception will be raised
       response.raise_for_status()

    except HTTPError as http_err:
       failed_result.append(http_err)
       print(f'HTTP error occurred: {http_err}')  
    except Exception as err:
       print(f'Other error occurred: {err}')  
    else:
       print('Success!')

這個 for 循環的作用是,它遍歷 a.csv 上的列並執行 get 調用以獲取狀態代碼。 現在,這還可以打印出按照執行順序指定的異常。 例如,如果列的前三行是:200,400,NaN -,則結果將是:成功、HTTP 錯誤和其他錯誤(分別)

期望的結果:我理解設計是按預期打印的——我希望所有輸出都存儲在一個變量/列表中,以便以后使用。 success, HTTP error, Other Error - 有沒有辦法做到這一點? 我嘗試append方法, pickle意味着我必須轉換為不理想的字典。 有沒有辦法在 Python 或 Pandas 中做到這一點?

另外,感謝這個文檔提供了 for 循環——它不是我的。 我在 Python 3.9 上使用 PyCharm。 我是新手,上周才開始,我發現了很多東西,但在我的特殊情況下找不到對我有幫助的答案。 也許我錯過了 - 道歉。

感謝任何可以提供幫助和建議的人!

您可以創建一個新列表,例如status_codes和 append 每次迭代后的狀態。 然后您可以使用zip()將 URL 和狀態碼綁定在一起,或者創建新的 dataframe。 例如:

import requests
from requests.exceptions import HTTPError

response_full_result = []

url_list = [
    "https://www.google.com",
    "https://www.yahoo.com",
    "https://xxx.domain.example",
]

status_codes = []  # <-- here we store status codes

for url in url_list:
    try:
        response = requests.get(url)
        response_full_result.append(response)

        # If the response was successful, no Exception will be raised
        response.raise_for_status()
    except HTTPError as http_err:
        failed_result.append(http_err)
        print(f"HTTP error occurred: {http_err}")
        status_codes.append("HTTP error")
    except Exception as err:
        print(f"Other error occurred: {err}")
        status_codes.append("Other error")
    else:
        print("Success!")
        status_codes.append("success")

print()

# print the results - use `zip()`
for url, status in zip(url_list, status_codes):
    print("{:<30} {}".format(url, status))

print()

# create a dataframe and write it to csv:
df = pd.DataFrame({"URL": url_list, "Status": status_codes})
print(df)
df.to_csv("data.csv", index=False)

印刷:

Success!
Success!
Other error occurred: HTTPSConnectionPool(host='xxx.domain.example', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f1e1c5e4100>: Failed to establish a new connection: [Errno -2] Name or service not known'))

https://www.google.com         success
https://www.yahoo.com          success
https://xxx.domain.example     Other error

                          URL       Status
0      https://www.google.com      success
1       https://www.yahoo.com      success
2  https://xxx.domain.example  Other error

並創建data.csv

URL,Status
https://www.google.com,success
https://www.yahoo.com,success
https://xxx.domain.example,Other error

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM