简单 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. 合法用途:请确保爬取行为用于学习、研究等合法用途,避免侵犯他人权益。

相关推荐
weixin_416639973 小时前
爬虫工程师Chrome开发者工具简单介绍
前端·chrome·爬虫
q5673152319 小时前
R语言初学者爬虫简单模板
开发语言·爬虫·r语言·iphone
泡泡以安2 天前
安卓高版本HTTPS抓包:终极解决方案
爬虫·https·安卓逆向·安卓抓包
q567315232 天前
Java Selenium反爬虫技术方案
java·爬虫·selenium
巴里巴气2 天前
Python爬虫用Clash软件设置代理IP
爬虫·python·tcp/ip
우리帅杰12 天前
爬虫002-----urllib标准库
爬虫
RacheV+TNY26427812 天前
拼多多API限流机制破解:分布式IP池搭建与流量伪装方案
大数据·网络·人工智能·爬虫·python
我怎么又饿了呀12 天前
DataWhale-零基础络网爬虫技术(三、爬虫进阶技术)
爬虫·datawhale
network爬虫12 天前
Python异步爬虫编程技巧:从入门到高级实战指南
开发语言·爬虫·python