requests() 函數(未完成)

requests可以用python來發送http請求,獲取並整理我們所需要的資料

import requests

url1 = "https://mimigd.com"
html1 = requests.get(url1)
#<Response [200]>
#把get到的存進變數html1中

if html1.status_code == requests.codes.ok:
    print("get成功")
#get到的話會返回成功訊息(200)



f1 = open("mimigd.html", "w" ,encoding="utf-8")
#打開mimigd.html,如沒有的話則創建一個(本地),以utf-8編碼開啟,存進f1變數裡
print(html1.text, file=f1)
#html1以text開啟並存進f1(mimigd.html)裡

「params=」、 headers =參數的輸入

import requests

url1 = "https://httpbin.org/get"
my_params = {
    "key1" : "value1",
    "key2" : "value2",
    "key3" : "value3"
}
#自訂參數(https://httpbin.org/get?key1=value1&key2=value2&key3=value3)
my_headers = {
    "user-agent" : "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
}
#自訂標頭,偽裝成iphone
html1 = requests.get(url1, params=my_params, headers=my_headers)
f1 = open("httpbin.html", "w", encoding="utf-8")
print(html1.text, file=f1)

發送POST請求:

import requests

url = 'https://httpbin.org/post'

my_payload = {
    'key1':'value1',
    'key2':'value2',
    'key3':'value3'
}
# 自訂cookie
cook = {
    'cookie1':'123',
    'cookie2':'456'
}

response = requests.post(url, data=my_payload, cookies=cook)

if response.status_code == requests.codes.ok:
    print(response.text)
else:
    print('failed')

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *