Python 爬虫基础教学

爬虫是自动从互联网上抓取数据的程序,Python 因其丰富的库和简洁语法成为爬虫开发的首选语言。下面我将介绍Python爬虫的基础知识。

一.基本组件

1. Requests库- 用于发送HTTP请求

2. BeautifulSoup库 - 用于解析HTML/XML文档

3. 正则表达式 - 用于提取特定模式的数据

二.安装必要库

bash

pip install requests beautifulsoup4 lxml

三.简单爬虫示例

python

import requests

from bs4 import BeautifulSoup

1. 发送HTTP请求获取网页内容

url = 'https://example.com'

response = requests.get(url)

检查请求是否成功

if response.status_code == 200:

2. 解析网页内容

soup = BeautifulSoup(response.text, 'lxml')

3. 提取所需数据

获取页面标题

title = soup.title.string

print(f"页面标题: {title}")

获取所有链接

links = soup.find_all('a')

for link in links:

print(link.get('href'))

else:

print(f"请求失败,状态码: {response.status_code}")

四.常用数据提取方法

python

通过标签名查找

soup.find('div') # 查找第一个div标签

soup.find_all('p') # 查找所有p标签

通过类名查找

soup.find_all(class_='class-name')

通过ID查找

soup.find(id='element-id')

通过CSS选择器查找

soup.select('div.content > p') # 查找div.content下的所有p标签

```

五.处理动态内容

对于JavaScript渲染的页面,可以使用Selenium:

python

from selenium import webdriver

from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get('https://example.com')

等待页面加载完成

driver.implicitly_wait(10)

查找元素

element = driver.find_element(By.TAG_NAME, 'h1')

print(element.text)

driver.quit()

六.爬虫伦理与法律注意事项

1. 尊重robots.txt - 遵守网站的爬虫规则

2. 设置合理的请求间隔 - 避免给服务器造成过大压力

3. 注明数据来源 - 如果公开使用爬取的数据

4. 不爬取敏感或个人数据 - 遵守隐私法律法规

5. 检查网站的使用条款- 确保爬虫行为不违反条款

七.高级技巧

1. 使用Session保持会话

2. 处理Cookies

3. 设置请求头模拟浏览器

4. 使用代理IP

5. 处理验证码

6. 数据存储(CSV, JSON, 数据库)

八.简单实战示例

python

import requests

from bs4 import BeautifulSoup

import csv

def simple_crawler(url, output_file):

设置请求头模拟浏览器

headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'

}

response = requests.get(url, headers=headers)

if response.status_code == 200:

soup = BeautifulSoup(response.text, 'lxml')

假设我们要提取所有新闻标题和链接

news_items = soup.select('.news-item') # 根据实际网站结构调整选择器

with open(output_file, 'w', newline='', encoding='utf-8') as file:

writer = csv.writer(file)

writer.writerow(['标题', '链接'])

for item in news_items:

title = item.select_one('h2').text.strip()

link = item.find('a')['href']

writer.writerow([title, link])

print(f"数据已保存到{output_file}")

else:

print("请求失败")

使用示例

simple_crawler('https://news.example.com', 'news_data.csv')

希望这份基础教学能帮助你入门Python爬虫开发!记得始终遵守法律和道德规范。

相关推荐
AI探索者16 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者17 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh18 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅18 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽19 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python