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

相关推荐
起个名字费劲死了5 小时前
Pytorch Yolov11 OBB 旋转框检测+window部署+推理封装 留贴记录
c++·人工智能·pytorch·python·深度学习·yolo·机器人
用户785127814705 小时前
淘宝获取商品详情数据API接口PC端和App端的实际操作指南
python
神仙别闹5 小时前
基于 Python 模式识别(纹理图片里的目标检测)
python·目标检测·目标跟踪
高山有多高6 小时前
从 0 到 1 保姆级实现C语言双向链表
c语言·开发语言·数据结构·c++·算法·visual studio
小小测试开发6 小时前
用Playwright实现接口自动化测试:从基础到实战
python·自动化·接口自动化·playwright
Lucis__6 小时前
C++相关概念与语法基础——C基础上的改进与优化
c语言·开发语言·c++
草莓熊Lotso6 小时前
《算法闯关指南:优选算法--滑动窗口》--14找到字符串中所有字母异位词
java·linux·开发语言·c++·算法·java-ee
hhcgchpspk6 小时前
flask获取ip地址各种方法
python·tcp/ip·flask
站大爷IP7 小时前
Python SQLite模块:轻量级数据库的实战指南
python
站大爷IP7 小时前
用Requests+BeautifulSoup实现天气预报数据采集:从入门到实战
python