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爬虫开发!记得始终遵守法律和道德规范。

相关推荐
树下水月2 分钟前
python 连接hive2 数据库
开发语言·数据库·python
小白宗轩3 分钟前
vsCode的java配置
java·vscode·python
Tom4i3 分钟前
Kotlin 中的 inline 和 reified 关键字
android·开发语言·kotlin
凄戚7 分钟前
bash和命令
开发语言·chrome·bash
Evan芙9 分钟前
Bash 变量命名规则与类型使用
linux·运维·开发语言·chrome·bash
在人间负债^27 分钟前
Rust 实战项目:TODO 管理器
开发语言·后端·rust
爱吃烤鸡翅的酸菜鱼34 分钟前
用【rust】实现命令行音乐播放器
开发语言·后端·rust
全栈陈序员34 分钟前
用Rust和Bevy打造2D平台游戏原型
开发语言·rust·游戏引擎·游戏程序
黛琳ghz34 分钟前
用 Rust 从零构建高性能文件加密工具
开发语言·后端·rust
悟世君子35 分钟前
Rust 开发环境搭建
开发语言·后端·rust