Python入门到实战:网络请求与数据获取

一、环境准备,安装requests库

1.安装命令(终端执行)

python 复制代码
 #安装requests库
pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple/
#(该方式是临时指定的,每次下载需要去cmd终端下载库 相对来说比较麻烦,每次添加库的时候就要去cmd终端去下载)

2.解决安装超时的问题(配置国内镜像源)

python 复制代码
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
说明:默认连接Python官方仓库,国内镜像源(如清华源)可提升下载速度。

二、基本用法:发起GET请求

1.导入模块与基础请求

python 复制代码
import requests #导入requests库
# 在要获取数据的浏览器页面里,找到目标URL(以疾病查询页面为例),键盘按下Fn+F12,查看是什么请求方式
url = 'https://www.youlai.cn/dise'
# 发起get请求,获取响应对象 将获取到的响应对象的结果给到变量res
res = requests.get(url) 
# 打印响应内容(如果响应结果是HTML文本内容)
print("响应内容:",res.text)

2.处理中文乱码问题

python 复制代码
import requests
url = 'https://www.tjwenming.cn/'
res = requests.get(url)
# 手动指定编码(根据目标网页的meta标签设置,此处以gb2312为例)
res.encoding = 'gb2312'
print('处理后的中午内容:',res.text)

调用encoding前 调用encoding后

关键步骤:
  • 检查网页源码中的<metacharset="xxx">标签,获取编码格式(如utf-8、gbk、gb2312)。
  • 通过response.encoding设置编码,确保中文正常显示。

三、带参数的GET请求

1.参数传递方式

方式一:URL拼接参数(直接在URL中携带参数)

python 复制代码
import requests
#包含参数的完整URL(从浏览器复制)
url='https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1763364793381&countryId=&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=&attrId=2,3&keyword=&pageIndex=1&pageSize=10&language=zh-cn&area=cn'
res = requests.get(url)
print(res.text)

方式二:通过params参数传递

python 复制代码
url = 'https://careers.tencent.com/tencentcareer/api/post/Query' # 注意写基础的URL 不带后面的请求参数
params = { # 将请求参数通过字典的形式存起来,给到params
    'timestamp': 1763364793381,
    'ountryId': '',
    'cityId': '',
    'bgIds': '',
    'productId': '',
    'categoryId': '',
    'parentCategoryId': '',
    'attrId': '2,3', # 注意参数为字符串类型
    'keyword': '',
    'pageIndex': 1,
    'pageSize': 10,
    'language': 'zh-cn',
    'area': 'cn'
}
# 发起请求时传递params参数
res = requests.get(url,params=params)
print(res.text)

四、获取二进制数据(图片、视频等)

:下载网络图片并保存

python 复制代码
import requests
url = 'http://pic.enorth.com.cn/005/026/920/00502692031_21660ab6.jpg'
res = requests.get(url)
#如果请求网址对应的数据为图片视频音频
#获取数据的方式:响应对象.content--->字节数据
res_img = res.content 
with open('1.jpg','wb') as f:
    f.write(res_img)
关键点:
  • 二进制数据通过response.content获取,而非text。
  • 文件扩展名需与内容类型匹配(如.gif、.mp4、.jpg)。
相关推荐
AI探索者3 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者3 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh5 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅5 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽6 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时10 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿12 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python