python监控网页变化
时间: 2023-08-11 10:03:15 浏览: 53
可以使用Python中的第三方库beautifulsoup4和requests来监控网页变化。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
import time
url = 'https://www.example.com'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 获取初始页面内容
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
initial_content = soup.prettify()
while True:
# 暂停1分钟
time.sleep(60)
# 获取最新页面内容
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
latest_content = soup.prettify()
# 比较页面内容是否有变化
if latest_content != initial_content:
print('网页内容已经发生变化!')
# 发送邮件或进行其他操作
break
# 更新初始页面内容
initial_content = latest_content
```
该代码会每隔1分钟获取一次指定网页的内容,并与初始页面内容进行比较,如果有变化则输出提示信息并退出循环。你可以根据需要对代码进行修改来实现更复杂的监控功能。