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

后面继续分享~

相关推荐
小白学大数据1 天前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
搂着猫睡的小鱼鱼1 天前
从选型到落地:京东评论爬虫开发历程(含反爬应对与经验总结)
爬虫
祭曦念1 天前
越权漏洞的克星!用爬虫自动化检测平行越权/垂直越权漏洞
爬虫·安全·自动化
qq_283720051 天前
Python 爬虫实战:从入门到精通,爬取某站数据
爬虫·逆向·反爬虫
深蓝电商API1 天前
反爬虫对抗策略在海淘场景的应用
爬虫·海淘·反爬
tang777891 天前
小红书平台用什么代理IP?数据采集IP封禁解决方法
数据库·爬虫·python·网络协议·ip
亿牛云爬虫专家1 天前
学术文献爬虫 OOM 崩溃与 403 风暴
爬虫·rust·爬虫代理·403·oom killer·学术文献·403 forbidden
嫂子的姐夫2 天前
33-补环境介绍
爬虫·js逆向·逆向
ZC跨境爬虫2 天前
Python异步IO详解:原理、应用场景与实战指南(高并发爬虫首选)
爬虫·python·算法·自动化
嫂子的姐夫2 天前
35-JS VMP技术介绍
爬虫·js逆向