简单 Python 爬虫程序设计

爬虫是获取网页数据的常用工具,我们一起来设计一个基于 requests 和 BeautifulSoup 的简单爬虫,它可以获取网页内容并提取文本信息。

所需库安装

首先需要安装两个必要的库:

pip install requests beautifulsoup4

完整代码

import requests

from bs4 import BeautifulSoup

import time

import random

import os

def simple_crawler(url, save_dir="crawled_data"):

"""

简单网页爬虫程序

:param url: 要爬取的网页URL

:param save_dir: 保存数据的目录

:return: 爬取的文本内容

"""

try:

模拟浏览器请求头,避免被识别为爬虫

headers = {

"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"

}

发送GET请求

response = requests.get(url, headers=headers, timeout=10)

检查请求是否成功

if response.status_code == 200:

设置正确的编码(处理中文乱码)

response.encoding = response.apparent_encoding

使用BeautifulSoup解析HTML

soup = BeautifulSoup(response.text, 'html.parser')

提取所有文本内容

all_text = soup.get_text()

创建保存目录(如果不存在)

if not os.path.exists(save_dir):

os.makedirs(save_dir)

保存内容到文件

filename = f"{save_dir}/{url.split('//')-1.split('/')0.replace('.', '')}{int(time.time())}.txt"

with open(filename, 'w', encoding='utf-8') as f:

f.write(all_text)

print(f"成功爬取并保存内容到 {filename}")

return all_text

else:

print(f"请求失败,状态码: {response.status_code}")

return None

except requests.exceptions.RequestException as e:

print(f"请求异常: {e}")

return None

except Exception as e:

print(f"发生错误: {e}")

return None

if name == "main":

要爬取的网址(请替换为你想爬取的合法网址)

target_url = "https://example.com"

执行爬取

content = simple_crawler(target_url)

if content:

打印前500个字符(可选)

print(f"\n爬取内容预览:\n{content:500}...")

代码功能解析

这个爬虫程序主要包含以下几个部分:

  • 请求头设置:模拟浏览器请求头,降低被网站反爬机制识别的概率

  • 请求发送:使用 requests 库发送HTTP GET请求获取网页内容

  • 内容解析:通过 BeautifulSoup 解析HTML,提取纯文本内容

  • 数据保存:将爬取的内容保存到本地文本文件中

  • 异常处理:包含请求异常和通用异常处理,增强程序稳定性

使用注意事项

  1. 替换URL:将代码中的 https://example.com 替换为你想爬取的合法网址

  2. 遵守规则:爬取前请阅读网站的 robots.txt ,遵守网站爬取规则

  3. 控制频率:代码中可添加 time.sleep(random.uniform(1, 3)) 来控制爬取间隔,避免对服务器造成压力

  4. 合法用途:请确保爬取行为用于学习、研究等合法用途,避免侵犯他人权益。

相关推荐
亿牛云爬虫专家6 小时前
聊聊数据的“冷热分离“:如何对历史爬虫数据进行合理的归档与压缩存储?
爬虫·爬虫代理·架构设计·隧道代理·大数据处理·压缩存储·数据分层存放
袁袁袁袁满6 小时前
Python爬虫实战:利用巨量IP获取跨境电商数据
爬虫·python·网络爬虫·爬虫实战·跨境电商·电商爬虫
拿本唠嗑AI研究8 小时前
现代前端架构爬虫指南:从静态页面到 React/Vue 单页应用
前端·爬虫·架构
一个处女座的程序猿1 天前
Crawler之Tool:MediaCrawler的简介、安装和使用方法、案例应用之详细攻略
爬虫·mediacrawler
深蓝电商API1 天前
Hook Canvas 获取浏览器指纹
爬虫·hook canvas
深蓝电商API1 天前
Hook Crypto API 获取加密参数
爬虫·hook crypto api
瓦学妹2 天前
Wikimon Scraper:用 Python 构建数据爬虫
开发语言·爬虫·python
小白学大数据3 天前
长周期爬虫的数据一致性:断点续爬 + 事务回滚保障采集质量
开发语言·爬虫·测试工具
跨境旺仔小拳头3 天前
Wikimon Scraper:用 Python 构建数据爬虫
数据库·爬虫·python
鬼手点金3 天前
Scrapy 网络爬虫框架
爬虫·python·scrapy·ajax·html·json·requsts