HTTP请求
折叠代码块PYTHON
复制代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| import json import requests
def httpRequest(): url = "https://www.so.com" headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 UOS" } getParams = { "q": "112" } postParams = { "q": "112" } jsonData = { "first": 1 } response = requests.request("GET", url, headers = headers, params=getParams, data=postParams, json=jsonData, timeout= 5) print(response.status_code) headers = response.headers for key in headers: print(f"{key}: {headers[key]}") responseText = response.text print(json.loads(response.text)) print(response.json().get("key")) with open("./test1.txt", "w", encoding="UTF-8") as file: for line in responseText: file.write(line) with open("./test2.txt", "wb") as file: file.write(response.content)
httpRequest()
|
HTTP请求视频流
在HTTP请求中,请求视频流时如果卡住,可以在requests.request添加stream=True
请求时手动携带cookie
折叠代码块PYTHON
复制代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import os import pickle import requests
def httpRequestWithCookie(): url = "https://www.so.com" if (os.path.exists("./cookies")): with open(f"./cookies", "rb",) as file: cookies = pickle.load(file) response = requests.get(url, cookies = cookies) else: response = requests.get(url) cookies = response.cookies with open(f"./cookies", "wb") as file: pickle.dump(cookies, file)
httpRequestWithCookie()
|
请求时自动携带cookie
折叠代码块PYTHON
复制代码
1 2 3 4 5 6 7 8 9
| import requests
def httpRequestWithSession(): url = "https://www.so.com" session = requests.session() response = session.request("GET", url); print(response.text)
httpRequestWithSession()
|
socks5代理
折叠代码块BASH
复制代码
1 2
| pip3 install requests[socks]
|
折叠代码块PYTHON
复制代码
1 2 3 4 5 6 7 8
| import requests
proxies = {'http' : 'socks5://127.0.00.1:1080', 'https': 'socks5://127.0.00.1:1080'}
url= 'http://test.com' r = requests.get(url, proxies=proxies) print(r.text)
|
v1.5.2