当前位置: 首页 > news >正文

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

http://www.dtcms.com/a/360881.html

相关文章:

  • C#/.NET/.NET Core技术前沿周刊 | 第 52 期(2025年8.25-8.31)
  • C++ 面试高频考点 力扣 35. 搜索插入位置 二分查找 左右端点查找 题解 每日一题
  • RocksDB 在 macOS M 系列 上运行时报错的解决方案
  • 【公告】更新预告
  • vite基础讲解
  • 超越Transformer:语言模型未来的认知革命与架构重构
  • Golang之GoWorld深度解析:基于Go语言的分布式游戏服务器框架
  • 新启航技术白皮书:激光频率梳如何实现 130mm 深孔 2μm 级无遮挡 3D 轮廓测量
  • OpenCV-Python Tutorial : A Candy from Official Main Page(五)
  • 使用Spring Boot对接印度股票市场API开发实践
  • Burp Suite 插件 | 提供强大的框架自动化安全扫描功能。目前支持1000+POC、支持动态加载POC、指定框架扫描。
  • 一体化运维平台自动化模块:3 大场景解放运维双手
  • 开发中使用——鸿蒙CoreSpeechKit语音识别
  • 复杂计算任务的智能轮询优化实战
  • 教育项目管理工具新趋势:可视化与自动化如何提升效率?
  • 使用ansible的playbook完成以下操作
  • TFS-2010《Fuzzy PCA-Guided Robust k-Means Clustering》
  • macOS中Homebrew安装PHP的详细步骤(五)
  • React学习教程,从入门到精通, React 入门指南:创建 React 应用程序的语法知识点(7)
  • 反物质量子比特初探
  • [免费]基于Python的气象天气预报数据可视化分析系统(Flask+echarts+爬虫) 【论文+源码+SQL脚本】
  • 【iOS】关键字复习
  • 【iOS】折叠cell
  • 量子電腦組裝
  • FunASR开源部署中文实时语音听写服务(CPU)
  • 配送算法19 Two Fast Heuristics for Online Order Dispatching
  • windows10专业版系统安装本地化mysql服务端
  • 【Docker】Docker的容器Container、镜像Image和卷Volume对比
  • Centos安装unoconv文档转换工具并在PHP中使用phpword替换word模板中的变量后,使用unoconv将word转换成pdf
  • openharmony之sandbox沙箱机制详解