一、爬虫基础概念
什么是爬虫?
网络爬虫(Web Crawler)是一种自动获取网页内容的程序,它像蜘蛛一样在互联网上'爬行',收集和提取数据。
爬虫应用场景
- 搜索引擎(Google、百度)
- 价格监控(电商比价)
- 舆情分析(社交媒体监控)
- 数据采集(研究、分析)
二、环境准备
1. 安装 Python
- 官网下载:Download Python | Python.org
- 安装时勾选'Add Python to PATH'
2. 安装必要库(命令行执行)
pip install requests beautifulsoup4 pandas
3. 安装开发工具(可选)
推荐使用 VS Code:Visual Studio Code - Code Editing. Redefined
三、第一个爬虫:获取网页标题
1. 创建文件 first_crawler.py
import requests
from bs4 import BeautifulSoup
# 目标网址
url = "https://example.com"
# 发送 HTTP 请求
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 解析 HTML 内容
soup = BeautifulSoup(response.text, 'html.parser')
# 提取网页标题
title = soup.title.string
print(f"网页标题:{title}")
else:
print(f"请求失败,状态码:{response.status_code}")
2. 运行爬虫
python first_crawler.py
输出结果
网页标题:Example Domain


