2022-08-23

【Python】requests 的應用

參考資料 ----

Requests 是一個 Python HTTP 庫,但不是內建,所以要另外安裝
  1.  
  2. #!/usr/bin/python
  3. #-*- coding:utf-8 -*-
  4.  
  5. import requests
  6.  
  7. # 最 陽春/基本 的語法
  8. # res = requests.get('https://網址,一定要 https')
  9. # print("res = "+res.text) # 顯示 server 傳來的字串內容
  10. # 如果網站用的是像 Let's Encrypt 的免費認證
  11. # 造成傳來的字串內容為 An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security. 的錯誤訊息
  12. # 可加下列的 headers
  13. headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:55.0) Gecko/20100101 Firefox/55.0', }
  14. res = requests.get('https://網址,一定要 https', headers=headers)
  15.  
  16.  
  17. param = {'參數名1':參數值1, '參數名2':參數值2}
  18. res = requests.get('https://網址,一定要 https', param, headers=headers) # 網址後帶參數 → https://網址?參數名1=參數值1&參數名2=參數值2
  19.  
  20.  
  21.  
  22. # print(res.json()) # 因為字串內容是 json, 所以這指令可顯示 json 內容
  23.  
  24. lstDataset = res.json() # 將 json 內容存入 list
  25. for row in lstDataset:
  26. print("prod no = "+row['prodno']+", prod name = "+row['prodname'])
  27.  




沒有留言:

張貼留言