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

后面继续分享~

相关推荐
海边的梦15 小时前
【无标题】
爬虫·网络爬虫
@我漫长的孤独流浪19 小时前
Python爬虫实战:从入门到精通
开发语言·爬虫·python
小白学大数据21 小时前
如何判断网站流量飙升是搜索引擎爬虫导致的?
爬虫·scrapy·搜索引擎·pycharm
devnullcoffee21 小时前
亚马逊ASIN数据批量采集技术选型:工具 vs 自建爬虫 vs Scrape API vs AI Agent完整对比
人工智能·爬虫·agent·亚马逊运营·openclaw·亚马逊 asin 数据采集
MuShan-bit21 小时前
CSDN-推荐开源项目-auto-x-to-wechat
爬虫·微信·开源·node.js·twitter
小鸡吃米…1 天前
Python 网络爬虫
开发语言·爬虫·python
anzhxu1 天前
maxun爬虫机器人介绍与部署
爬虫
小心我捶你啊1 天前
提升爬虫稳定性的关键,Python爬虫代理IP解析与轮换策略
爬虫·python·tcp/ip
xdl25992 天前
【Python学习】网络爬虫-爬取豆瓣电影评论
爬虫·python·学习
袁袁袁袁满2 天前
基于亮数据MCP与LangGraph集成实现爬虫自动化
爬虫·python·网络爬虫·数据采集·爬虫实战·自动化采集·爬虫案例