2023-08-31|閱讀時間 ‧ 約 2 分鐘

小白學Python的第十八堂課

    在這一課中,我們將學習如何在Python中使用requests模塊發送HTTP請求。

    1. 發送GET請求requests.get() 函數用於發送GET請求。
    • 檔名: get_request.py
    pythonCopy code
    import requests

    response = requests.get('https://api.github.com')

    # 輸出 HTTP 狀態碼
    print(response.status_code)

    # 輸出回應的文字內容
    print(response.text)

    # 輸出: GitHub的API回應
    1. 發送POST請求requests.post() 函數用於發送POST請求。
    • 檔名: post_request.py
    pythonCopy code
    import requests

    response = requests.post('https://httpbin.org/post', data={'key': 'value'})

    # 輸出 HTTP 狀態碼
    print(response.status_code)

    # 輸出回應的文字內容
    print(response.text)

    # 輸出: httpbin的API回應

    請在相應的檔案中輸入並運行上述代碼片段。網路請求是Python編程的一個重要組件,這些範例應該幫助你上手。

    分享至
    成為作者繼續創作的動力吧!
    © 2024 vocus All rights reserved.