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

后面继续分享~

相关推荐
yijianace2 小时前
Python爬虫实战:分页爬取 + 详情页采集 + CSV存储
前端·爬虫·python
yijianace4 小时前
Python爬虫实战:ThreadPoolExecutor多线程采集书籍信息与图片下载
开发语言·爬虫·python
在放️4 小时前
Python 爬虫 · bs4 模块基础
开发语言·爬虫·python
belong_my_offer4 小时前
Python 数据采集完全指南 —— 从零开始掌握网络爬虫与文件读取
开发语言·爬虫·python
深蓝电商API4 小时前
Playwright vs Puppeteer vs Selenium 2026终极对比
爬虫·selenium·puppeteer·playwright
遇事不決洛必達12 小时前
【Python基础】GIL 锁是什么及其对爬虫的影响
爬虫·python·线程·进程·gil锁
綝~13 小时前
爬虫数据采集工程师岗位面试题
爬虫·面试·请求
跨境数据猎手14 小时前
大数据在电商行业的应用
大数据·运维·爬虫
tang7778920 小时前
异步爬虫与代理IP池结合:用aiohttp提升10倍抓取效率
爬虫·网络爬虫·爬虫代理·代理ip·代理ip池
深蓝电商API1 天前
行为模拟的艺术:如何让爬虫的鼠标轨迹像真人
爬虫