想抓取网站数据却不知道从何下手?这篇带你从零开始,写出第一个爬虫程序!
爬虫(Spider/Scraper) = 自动化程序 + 模拟浏览器访问 + 提取数据
1 2 3
| 我们的电脑 ──请求──> 网站服务器 <─返回网页HTML── ──解析提取──> 有用数据
|
爬虫能干什么?
| 应用场景 |
例子 |
| 数据采集 |
爬取新闻、房价、股票数据 |
| 内容抓取 |
下载图片、视频、文献 |
| 价格监控 |
电商商品价格变动提醒 |
| 搜索引擎 |
百度、Google的爬虫 |
| 数据分析 |
获取数据做分析报告 |
二、准备工作
1. 安装Python库
1 2 3 4 5
| pip install requests
pip install beautifulsoup4 lxml
|
2. 认识HTTP请求
我们访问网页,本质上是在发送HTTP请求:
| 请求方法 |
用途 |
例子 |
| GET |
获取数据 |
访问网页、查询信息 |
| POST |
提交数据 |
登录、提交表单 |
三、第一个爬虫: requests库基础
1. 最简单的GET请求
1 2 3 4 5 6 7 8 9 10 11 12 13
| import requests
response = requests.get('https://www.example.com')
print(response.status_code)
print(response.text)
print(response.content)
|
2. 带请求头的请求
很多网站会检测请求头,如果发现是爬虫会拒绝访问:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import requests
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' }
response = requests.get( 'https://www.example.com', headers=headers )
print(response.status_code) print(response.text)
|
3. 带参数的请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import requests
params = { 'wd': 'Python爬虫', 'pn': 10 }
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' }
response = requests.get( 'https://www.baidu.com/s', params=params, headers=headers )
print(response.url)
|
四、数据解析:BeautifulSoup入门
网页返回的是HTML代码,我们需要从中提取有用信息。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| from bs4 import BeautifulSoup
html = """ <html> <body> <div class="article"> <h1>文章标题</h1> <p class="content">这是文章内容</p> <a href="https://example.com">链接</a> </div> </body> </html> """
soup = BeautifulSoup(html, 'lxml')
print(soup.h1) print(soup.p)
print(soup.h1.text) print(soup.p.get_text())
article = soup.find('div', class_='article') print(article.text)
link = soup.find('a') print(link['href'])
all_links = soup.find_all('a') for link in all_links: print(link['href'])
|
常用查找方法
| 方法 |
作用 |
find() |
找到第一个 |
find_all() |
找到所有 |
select() |
CSS选择器 |
1 2 3 4 5
| soup.select('.article') soup.select('#header') soup.select('div > a') soup.select('a[href="xxx"]')
|
五、实战:爬取简单网页
目标:爬取一个简单的文章页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import requests from bs4 import BeautifulSoup
url = 'https://example.com/blog/article-1'
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' }
response = requests.get(url, headers=headers) response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'lxml')
title = soup.find('h1').text content = soup.find('div', class_='content').text date = soup.find('time').text
print(f'标题: {title}') print(f'发布时间: {date}') print(f'内容: {content[:100]}...')
|
六、常见问题
| 问题 |
原因 |
解决方法 |
| 乱码 |
编码问题 |
response.encoding = 'utf-8' |
| 403错误 |
被识别为爬虫 |
加User-Agent、换IP |
| 404错误 |
页面不存在 |
检查URL是否正确 |
| 速度慢 |
请求太频繁 |
加延时 time.sleep(1) |
| 找不到元素 |
网页结构变了 |
检查HTML,用开发者工具看结构 |
延时和异常处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import requests from bs4 import BeautifulSoup import time
url = 'https://example.com/page'
try: response = requests.get(url, timeout=10) response.raise_for_status() soup = BeautifulSoup(response.text, 'lxml') print('爬取成功') except requests.exceptions.RequestException as e: print(f'请求失败: {e}')
time.sleep(2)
|
七、写在最后
第一篇爬虫入门核心就这些:
1
| requests发送请求 → BeautifulSoup解析 → 提取数据
|
下篇预告:爬取图片/文件下载、多页面翻页爬取、存储到本地。
如果这篇文章对你有帮助,欢迎点赞+在看👍
有问题欢迎留言,我们一起进步!
#AI学习 #Python爬虫 #requests #BeautifulSoup #数据分析