Python爬虫入门:从零到数据采集

Python爬虫基础指南

Python爬虫是自动化获取网络数据的技术,广泛应用于数据采集、市场分析等领域。以下是核心实现步骤:

1. 核心库选择
python 复制代码
import requests  # 发送HTTP请求
from bs4 import BeautifulSoup  # HTML解析
import pandas as pd  # 数据存储
2. 基础爬取流程
python 复制代码
# 发送请求
response = requests.get("https://example.com/books")
response.encoding = 'utf-8'  # 设置编码

# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')

# 数据提取示例
book_titles = [h2.text for h2 in soup.select('.book-title')]
book_prices = [float(div.text.strip('¥')) 
               for div in soup.select('.price')]

# 存储数据
df = pd.DataFrame({'书名': book_titles, '价格': book_prices})
df.to_csv('book_data.csv', index=False)
3. 关键技巧
  • 反爬应对

    python 复制代码
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
        'Cookie': 'sessionid=abc123'
    }
    response = requests.get(url, headers=headers)
  • 动态页面处理(使用Selenium):

    python 复制代码
    from selenium import webdriver
    driver = webdriver.Chrome()
    driver.get(url)
    dynamic_content = driver.find_element_by_class('js-loaded-data').text
4. 完整案例:豆瓣图书爬虫
python 复制代码
def douban_spider():
    url = "https://book.douban.com/top250"
    res = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
    soup = BeautifulSoup(res.text, 'lxml')
    
    books = []
    for item in soup.select('.item'):
        title = item.select_one('.pl2 a')['title']
        rating = item.select_one('.rating_nums').text
        books.append((title, float(rating)))
    
    return pd.DataFrame(books, columns=['书名', '评分'])

df = douban_spider()
df.to_excel('豆瓣图书TOP250.xlsx')
5. 注意事项
  1. 遵守规则

    • 检查robots.txt(如https://site.com/robots.txt
    • 设置请求间隔:time.sleep(random.uniform(1,3))
  2. 异常处理

    python 复制代码
    try:
        response = requests.get(url, timeout=10)
    except (requests.ConnectionError, requests.Timeout) as e:
        print(f"请求失败: {str(e)}")
  3. 数据清洗

    python 复制代码
    # 去除空白字符
    clean_text = re.sub(r'\s+', ' ', raw_text).strip()

提示:对于复杂网站建议使用Scrapy框架,其内置的异步处理、管道机制和中间件能显著提升效率。

相关推荐
xiao5kou4chang6kai41 天前
MATLAB机器学习、深度学习--从数据预处理到模型训练
深度学习·机器学习·matlab·数据预处理
renhongxia12 天前
世界模型作为AGI落地底层底座的作用
人工智能·深度学习·生成对抗网络·自然语言处理·知识图谱·agi
计算机科研狗@OUC2 天前
(cvpr26) AIMDepth: Asymmetric Image-Event Mamba for Monocular Depth Estimation
人工智能·深度学习·计算机视觉
β添砖java2 天前
深度学习(22)网络中的网络NiN
人工智能·深度学习
Kobebryant-Manba2 天前
深度学习时候d2l报错和使用问题
人工智能·深度学习
zhangfeng11332 天前
deepspeed zero3 结合 llamafactory 微调 ,save_only_model: true 导致保存时候出错
开发语言·python·深度学习
大模型最新论文速读2 天前
06-16 · LLM 最新论文速览
论文阅读·人工智能·深度学习·机器学习·自然语言处理
宝贝儿好2 天前
【LLM】第二章:HuggingFace入门学习
人工智能·深度学习·神经网络·学习·算法·自然语言处理
Black蜡笔小新2 天前
企业私有化AI训练推理一体工作站DLTM深度学习推理工作站全流程技术解析
人工智能·深度学习
Kobebryant-Manba2 天前
学习门控循环单元gru
深度学习·学习·gru