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'  # 可以修改编码

后面继续分享~

相关推荐
VW_4048 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
tryCbest17 小时前
Python 爬虫从入门到实战(二):进阶篇——反爬对抗、并发与动态页面
开发语言·爬虫·python
乌鲁木齐德润恒圣信息科技有限公司2 天前
AI爬虫怎么读你的网站:结构化标记实操
人工智能·爬虫
乌鲁木齐德润恒圣信息科技有限公司2 天前
智推纪元 子站架构技术拆解
大数据·人工智能·爬虫
tryCbest3 天前
Python 爬虫从入门到实战(一):基础篇——从零写出第一个爬虫
开发语言·爬虫·python
wuyk5553 天前
Spider-第20讲-综合实战可上线爬虫
大数据·爬虫·python·elasticsearch
wuyk5555 天前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
wuyk5556 天前
Spider-第14讲-表单提交与CSRF
前端·爬虫·python·elasticsearch·csrf
wuyk5559 天前
Spider-第11讲-工程化改造与可维护性
大数据·爬虫·elasticsearch·搜索引擎
wuyk5559 天前
Spider-第12讲-asyncio异步并发爬取
大数据·爬虫·elasticsearch·搜索引擎