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 小时前
爬虫基础学习 - Beautifulsoup
爬虫·学习·beautifulsoup
dbdr09012 小时前
Linux 入门到精通,真的不用背命令!零基础小白靠「场景化学习法」,3 个月拿下运维 offer,第二十四天
linux·运维·c语言·python·学习
烟雨迷2 小时前
web自动化测试(selenium)
运维·开发语言·前端·python·selenium·测试工具
潼心1412o4 小时前
C语言(长期更新)第12讲:指针二详解
c语言·开发语言
荼蘼4 小时前
Python 爬虫实战:爬取 B 站视频的完整教程
开发语言·爬虫·python
XYiFfang4 小时前
【Python+requests】解决Python requests中的ProxyError:SSL版本错误问题详解
python·debug·ssl·常见错误·代理配置
huluang4 小时前
VibeVoice 部署全指南:Windows 下的挑战与完整解决方案
windows·python
AI Echoes4 小时前
一款为开发者而生的开源全栈LLMOps平台
人工智能·python·langchain·agent
玉木子4 小时前
机器算法(五)模型选择与调优
人工智能·python·深度学习·算法·机器学习