python发送request请求

安装request

执行命令

1
pip install requests

提示:如果出现
ERROR: Could not find a version that satisfies the requirement requests (from versions: none)
ERROR: No matching distribution found for requests
[notice] A new release of pip is available: 23.1.2 -> 23.2.1
[notice] To update, run: python.exe -m pip install --upgrade pip
错误 升级一下pip 执行 python.exe -m pip install --upgrade pip

使用request
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import requests
response = requests.get('https://books.toscrape.com/')
if response.ok:
# 代码内容
print(response.text)
else:
print('请求失败')


# 可以定义head参数
head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
response = requests.get('https://books.toscrape.com/',headers=head)
if response.ok:
# 代码内容
print(response.text)
else:
print('请求失败')