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

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

admin4周前 (03-18)Python43

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 教程] Matplotlib 数据可视化教程

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

Python 装饰器实用技巧:从入门到精通

装饰器是 Python 最强大的特性之一,但也是很多开发者感到困惑的概念。简单来说,装饰器是一个函数,它接受另一个函数作为输入,并返回一个新的函数。使用装饰器,你可以在不修改原函数代码的情况下,为其添...

Python 上下文管理器实战:从 with 语句到自定义资源管理

在 Python 编程中,上下文管理器(Context Manager)是一个强大但常被低估的特性。当你使用 open() 函数读取文件时,那个熟悉的 with 语句背后,正是上下文管理器在默默工作。...

Python 装饰器完全指南:从入门到实战

装饰器本质上是一个接受函数作为参数并返回新函数的高阶函数。理解这一点是掌握装饰器的关键。想象一下,你有一个函数,你想在它执行前后添加一些额外的逻辑,比如日志记录、性能测试、权限验证等。装饰器就是为这种...

Python 装饰器进阶:从入门到实战,写出更灵活的函数增强技巧

# Python 装饰器进阶:从入门到实战,写出更灵活的函数增强技巧 ## 简介 很多 Python 开发者都听过装饰器,也知道怎么写简单的装饰器。但大多数人对装饰器的进阶用法,比如带参数的装饰器、...

Python异步编程入门与实战

异步编程是一种并发执行的编程模式,它允许程序在等待耗时操作(如网络请求、文件读写)时,继续执行其他任务。Python 3.5引入了async/await语法,使得异步编程变得更加直观和易于理解。为什么...

发表评论

访客

看不清,换一张

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