编写网页监控程序的基本步骤如下:
环境准备
安装Python,推荐使用3.7以上版本。
安装必要的库,如`requests`用于发送HTTP请求,`BeautifulSoup`用于解析HTML内容,`smtplib`用于发送邮件等。可以使用以下命令安装这些库:
```bash
pip install requests beautifulsoup4 schedule
```
抓取网页内容
使用`requests`库发送GET请求获取网页内容。例如:
```python
import requests
def get_web_content(url):
try:
response = requests.get(url)
response.raise_for_status() 检查请求是否成功
return response.text
except requests.exceptions.RequestException as e:
print(f"抓取网页失败: {e}")
return None
```
解析网页内容
使用`BeautifulSoup`库解析抓取到的HTML内容,提取有用信息。例如:
```python
from bs4 import BeautifulSoup
def extract_info(html_content):
soup = BeautifulSoup(html_content, 'html.parser')
提取所需信息,例如标题、文本等
title = soup.title.string if soup.title else "无标题"
return title
```
检查网页变化
可以通过计算网页内容的哈希值来检测内容是否有变化。例如:
```python
import hashlib
def get_content_hash(content):
if content:
return hashlib.md5(content.encode('utf-8')).hexdigest()
return None
def check_changes(url, old_hash):
content = get_page_content(url)
current_hash = get_content_hash(content)
if current_hash != old_hash:
print(f"网页内容发生变化: {url}")
return True
return False
```
定时执行监控
使用`schedule`库或其他定时任务工具(如Linux的cron)定期执行监控任务。例如:
```python
import schedule
import time
def monitor_website(url, interval=60):
while True:
if check_changes(url, old_hash): 假设old_hash是之前记录的哈希值
send_email_notification(url) 发送邮件通知的函数
time.sleep(interval)
schedule.every(1).minutes.do(monitor_website, url="https://www.example.com")
while True:
schedule.run_pending()
time.sleep(1)
```
发送邮件通知
使用`smtplib`库发送邮件通知。例如:
```python
import smtplib
from email.mime.text import MIMEText
def send_email_notification(url):
msg = MIMEText(f"网页 {url} 内容发生变化")
msg['Subject'] = '网页监控通知'
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient_email@example.com'
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login('your_email@example.com', 'your_password')
server.sendmail('your_email@example.com', 'recipient_email@example.com', msg.as_string())
```
以上是一个简单的网页监控程序的基本框架。根据具体需求,可以进一步扩展和优化,例如增加对不同状态码的处理、支持多种通知方式(如短信、微信等)、集成第三方监控服务等。