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框架,其内置的异步处理、管道机制和中间件能显著提升效率。

相关推荐
lingchen19063 小时前
卷积神经网络中的卷积运算原理
深度学习·计算机视觉·cnn
MYX_3095 小时前
第七章 完整的模型训练
pytorch·python·深度学习·学习
渡我白衣5 小时前
深度学习进阶(八)——AI 操作系统的雏形:AgentOS、Devin 与多智能体协作
人工智能·深度学习
CLubiy5 小时前
【研究生随笔】Pytorch中的线性代数
pytorch·python·深度学习·线性代数·机器学习
材料科学研究5 小时前
深度学习物理神经网络(PINN)!
python·深度学习·神经网络·pinn
渡我白衣6 小时前
深度学习进阶(七)——智能体的进化:从 LLM 到 AutoGPT 与 OpenDevin
人工智能·深度学习
聚梦小课堂6 小时前
ComfyUI Blog: ImagenWorld 发布:面向图像生成与编辑的真实世界基准测试数据集
人工智能·深度学习·图像生成·benchmark·imagenworld
闲人编程7 小时前
深入浅出Transformer:使用Hugging Face库快速上手NLP
python·深度学习·自然语言处理·nlp·transformer·hugging face·codecapsule
XIAO·宝7 小时前
深度学习------YOLOV1和YOLOV2
人工智能·深度学习·yolo