python--爬虫入门

一、request库介绍

Requests 是 Python 中最受欢迎的 HTTP 客户端库,它提供了简单易用的 API 来处理 HTTP 请求,让发送 HTTP/1.1 请求变得异常简单。

主要特点

  • 简单易用:人性化的 API 设计,代码直观易懂

  • 功能全面:支持 HTTP 所有主要方法、身份验证、Cookies、代理等

  • 自动处理:自动处理 URL 编码、连接池管理、重定向等

  • 社区活跃:有丰富的文档和活跃的社区支持

示例代码:

1.发送get请求

python 复制代码
import requests
response = requests.get("****")
print(response.status_code)
print(response.text)
复制代码
response.status_code为返回的状态码,response.text为响应内容
python 复制代码
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('*****', params=params)

2.发送POST请求

python 复制代码
import requests

# 表单数据
data = {'username': 'admin', 'password': 'secret'}
response = requests.post('******', data=data)

# JSON 数据
json_data = {'name': 'John', 'age': 30}
response = requests.post('******', json=json_data)

# 文件上传
files = {'file': open('example.txt', 'rb')}
response = requests.post('******', files=files)

3.其他HTTP方法

python 复制代码
import requests

# PUT 请求
response = requests.put('******/put', data={'key': 'value'})

# DELETE 请求
response = requests.delete('******/delete')

# PATCH 请求
response = requests.patch('******/patch', data={'update': 'data'})

# HEAD 请求(只获取响应头)
response = requests.head('*******/get')

4.响应处理

python 复制代码
import requests

response = requests.get('******')

# 状态码和状态信息
print(f"状态码: {response.status_code}")
print(f"状态信息: {response.reason}")

# 响应内容
print(f"文本内容: {response.text}")          # 字符串格式
print(f"二进制内容: {response.content}")     # 字节格式
# print(f"JSON内容: {response.json()}")        # JSON 格式(自动解析)

# 响应头
print(f"响应头: {response.headers}")
print(f"Content-Type: {response.headers['Content-Type']}")

# Cookies
print(f"Cookies: {response.cookies}")

# 编码
print(f"编码: {response.encoding}")
response.encoding = 'utf-8'  # 可以修改编码

后面继续分享~

相关推荐
WL_Aurora4 小时前
Python爬虫实战(六):新发地蔬菜价格数据采集.
爬虫·python
盲敲代码的阿豪4 小时前
Python 入门基础教程(爬虫前置版)
开发语言·爬虫·python
深蓝电商API9 小时前
电商网站行为检测绕过:鼠标轨迹模拟 + 点击热区分析
爬虫
深蓝电商API13 小时前
移动端APP抓包实战:Frida+SSL Pinning绕过的完整配置
爬虫
枫叶V16 小时前
Scrapling 入门:一个现代 Python 网页采集框架
后端·爬虫
YYueHua516 小时前
python3爬虫基础--HTTP基本原理
爬虫
靠谱品牌推荐官17 小时前
【架构实战】如何设计一套原生支持 GEO 大模型爬虫语义索引的 HTML5/CSS3 纯净白盒前端架构?
前端·爬虫·架构
烟雨江南aabb17 小时前
Python第七弹:爬虫篇:BeautifulSoup库
爬虫·python·beautifulsoup
深蓝电商API1 天前
请求签名算法破解:从Chrome DevTools到Python还原的完整流程
爬虫·反爬
DevnullCoffe2 天前
用 MCP 让 AI Agent 直接批量下载亚马逊商品图片——原理、踩坑与实现
爬虫·python·api