碎片时间学Python-04发送请求(python发送信号)
本集是对前面知识的串讲。主要包括:
1. 验证Python是否安装成功
打开终端,输入python,如果出现Python版本信息,则安装成功。
2. 理解虚拟环境
- 在命令窗口使用pip install requests 命令安装requests库,由于没有指定任何环境,所以默认安装到全局环境中。
- 创建一个文件夹名为 04_send_request,进入该文件夹下,使用venv创建一个虚拟环境myenv。
- 在myenv环境下,使用pip list 命令查看当前环境安装的库。由于之前安装requests的环境和myenv环境不是同一个,所以看不到requests库。
3. 使用pip
- 在myenv环境下,使用pip install requests 命令安装requests库。
- 使用pip list 命令查看当前环境安装的库,确保requests库已经安装。
4. 发送一个网络请求
import requests
# 请求百度首页
response = requests.get('https://www.baidu.com')
# 打印请求返回的内容
print(response.text)
打印输出:
<html>
<head>
<script>
location.replace(location.href.replace("https://","http://"));
</script>
</head>
<body>
<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>