当前位置:首页 > Python > 正文内容

[Python 教程] Python 网络请求与爬虫基础

admin3小时前Python3

Python 网络请求与爬虫基础

requests 是 Python 最常用的 HTTP 库。本文介绍网络请求和爬虫的基础知识。

一、基础请求

import requests

# GET 请求
response = requests.get('https://api.example.com/data')
print(response.status_code)  # 状态码
print(response.text)         # 响应文本
print(response.json())       # JSON 响应

# 带参数
params = {'q': 'python', 'page': 1}
response = requests.get('https://api.example.com/search', params=params)

# POST 请求
data = {'username': 'user', 'password': 'pass'}
response = requests.post('https://api.example.com/login', data=data)

二、请求头

headers = {
    'User-Agent': 'Mozilla/5.0',
    'Accept': 'application/json',
    'Authorization': 'Bearer token123'
}

response = requests.get('https://api.example.com/data', headers=headers)

三、会话管理

session = requests.Session()

# 保持会话(自动处理 cookies)
session.get('https://example.com/login', data={'user': 'admin'})
response = session.get('https://example.com/profile')

# 使用上下文
with requests.Session() as session:
    session.get('https://example.com')

四、文件上传

# 上传文件
files = {'file': open('report.xls', 'rb')}
response = requests.post('https://example.com/upload', files=files)

# 下载文件
response = requests.get('https://example.com/image.jpg')
with open('image.jpg', 'wb') as f:
    f.write(response.content)

五、异常处理

try:
    response = requests.get('https://api.example.com', timeout=5)
    response.raise_for_status()  # 检查状态码
except requests.exceptions.Timeout:
    print('请求超时')
except requests.exceptions.HTTPError as e:
    print(f'HTTP 错误:{e}')
except requests.exceptions.RequestException as e:
    print(f'请求异常:{e}')

六、简单爬虫示例

from bs4 import BeautifulSoup

def crawl_page(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 提取所有链接
    links = soup.find_all('a')
    for link in links:
        href = link.get('href')
        text = link.get_text(strip=True)
        print(f'{text}: {href}')

crawl_page('https://example.com')
返回列表

上一篇:[Python 教程] Python 多线程编程指南

没有最新的文章了...

相关文章

[Python 教程] OpenCV-Python 入门:图像处理基础详解

OpenCV-Python 入门:图像处理基础详解OpenCV 是一个跨平台计算机视觉库,轻量级且高效,支持 Python 接口。本文将系统介绍 OpenCV 的核心概念和基础操作。一、OpenCV...

[Python 教程] OpenCV 实战:图像与视频文件处理

OpenCV 实战:图像与视频文件处理本文详细介绍如何使用 OpenCV 处理图像和视频文件,包括读取、显示、保存等操作。一、图像文件操作1.1 读取图像import cv2 #&nb...

[Python 教程] OpenCV 绘图教程:图形与文本标注

OpenCV 绘图教程:图形与文本标注本文介绍如何在 OpenCV 中绘制各种图形和添加文本,用于图像标注和可视化。一、绘制基本图形1.1 创建画布import cv2 import&nb...

[Python 教程] NumPy 数组操作详解

NumPy 数组操作详解 NumPy 是 Python 科学计算的基础库,提供高性能的多维数组对象。本文详细介绍 NumPy 数组的核心操作。 一、创建数组 import numpy as np...

[Python 教程] Pandas 数据分析实战

Pandas 数据分析实战 Pandas 是 Python 数据分析的核心库,提供 DataFrame 和 Series 数据结构。本文介绍 Pandas 的实用技巧。 一、创建 DataFrame...

[Python 教程] Matplotlib 数据可视化教程

Matplotlib 数据可视化教程 Matplotlib 是 Python 最常用的绘图库。本文介绍常用图表的绘制方法。 一、基础设置 import matplotlib.pyplot as pl...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。