### 安装request库
| pip --default-timeout=100 install requests -i http: |
简单案例
| import requests |
| |
| url = "http://www.baidu.com" |
| headers = { |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36' |
| } |
| r = requests.get(url=url,headers=headers) |
| result = r.text |
| print(result) |
请求方式
| |
| |
| r = requests.get('https://github.com/timeline.json') |
| |
| r = requests.post("http://m.ctrip.com/post") |
| |
| r = requests.put("http://m.ctrip.com/put") |
| |
| r = requests.delete("http://m.ctrip.com/delete") |
| |
| r = requests.head("http://m.ctrip.com/head") |
| |
| r = requests.options("http://m.ctrip.com/get") |
获取响应信息
| |
| r.encoding |
| |
| r.encoding = 'utf-8' |
| |
| |
| r.text |
| |
| r.content |
| |
| |
| r.headers |
| |
| |
| r.status_code |
| |
| |
| r.raw |
| |
| |
| r.ok |
| |
| |
| r.json() |
| |
| |
| r.raise_for_status() |
| |
| |
| r.requests.headers |
| |
| |
| r.cookies |
| |
| |
| r.history |
格式化谷歌浏览器复制的请求头信息

| info = '''Host: www.baidu.com |
| Referer: https://www.baidu.com/s?ie=UTF-8&wd=%E7%9F%A5%E4%B9%8E |
| Sec-Fetch-Mode: navigate |
| Sec-Fetch-Site: none |
| Sec-Fetch-User: ?1 |
| Upgrade-Insecure-Requests: 1 |
| User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36''' |
| |
| infoDic = {} |
| |
| for e in info.split("\n"): |
| k,v = e.split(":",1) |
| infoDic[k] = v.strip() |
| |
| print(infoDic) |
| {'Host': 'www.baidu.com', 'Referer': 'https://www.baidu.com/s?ie=UTF-8&wd=%E7%9F%A5%E4%B9%8E', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Site': 'none', 'Sec-Fetch-User': '?1', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'} |
cookies的解析和上面的思路类似。
传递请求参数
| import requests |
| import json |
| |
| url = "http://www.baidu.com" |
| |
| headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'} |
| |
| params = {'keyword': '香港', 'salecityid': '2'} |
| |
| |
| cookies = {'BAIDUID':'88347BA2440BB05F7EF04EC4186904F4:FG=1'} |
| |
| |
| proxies = { |
| "http": "http://10.10.1.10:3128", |
| "https": "http://10.10.1.100:4444", |
| } |
| |
| r1 = requests.get( |
| url = url, |
| headers=headers, |
| params=params, |
| cookies=cookies, |
| |
| ) |
| print(r1.text) |
| |
| r2 = requests.post( |
| url = url, |
| headers=headers, |
| data=json.dumps(params) |
| ) |
| |
| print(r2.text) |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步