数据采集爬虫基础

Python数据分析入门Python

问题

如何用Python采集网络数据?

答题要点

import requests
import pandas as pd
from bs4 import BeautifulSoup
import time

# 基础爬取
def fetch_page(url):
    """爬取单个页面"""
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    response = requests.get(url, headers=headers, timeout=10)
    response.encoding = 'utf-8'
    return response.text

# 解析HTML
def parse_html(html):
    """解析HTML提取数据"""
    soup = BeautifulSoup(html, 'html.parser')

    # 提取标题
    titles = [tag.text.strip() for tag in soup.find_all('h2', class_='title')]

    # 提取价格
    prices = [tag.text.strip() for tag in soup.find_all('span', class_='price')]

    return pd.DataFrame({'title': titles, 'price': prices})

# API采集(推荐)
def fetch_api_data(api_url, params=None):
    """调用API获取JSON数据"""
    response = requests.get(api_url, params=params)
    data = response.json()
    return pd.DataFrame(data['results'])

# 带重试的爬取
def fetch_with_retry(url, max_retries=3):
    """带重试机制的爬取"""
    for i in range(max_retries):
        try:
            response = requests.get(url, timeout=10)
            if response.status_code == 200:
                return response.text
        except Exception as e:
            print(f"第{i+1}次重试失败: {e}")
            time.sleep(2 ** i)  # 指数退避
    return None

# 批量爬取
def batch_fetch(urls, delay=1):
    """批量爬取多个URL"""
    results = []
    for url in urls:
        html = fetch_page(url)
        df = parse_html(html)
        results.append(df)
        time.sleep(delay)  # 避免封IP

    return pd.concat(results, ignore_index=True)

# 使用示例
# 爬取示例API(公开数据)
api_url = 'https://api.example.com/products'
df = fetch_api_data(api_url, params={'category': 'electronics', 'page': 1})

# 保存数据
df.to_csv('scraped_data.csv', index=False)

# 注意事项
"""
1. 遵守robots.txt
2. 设置User-Agent
3. 控制请求频率(time.sleep)
4. 异常处理和重试
5. 优先使用API而非爬虫
6. 大规模爬取用Scrapy框架
"""

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题