我得到了一个文件找不到错误,标题上的那个,我是一个初学者. 有人能帮忙吗?

import requests
import time
from bs4 import BeautifulSoup

Headers = {"user-agent":"my user-agent"}

URL = "www.myurl.com"

def monitor_website_changes():
    while True:
        r = requests.get(URL, headers=Headers)
        with open("website_content.txt", "r") as file:
            previous_content = file.read()
        if response.txt == previous_content:
            print("website content has changed")
        with open("website_content.txt", "w") as file:
            file.write(response.txt)
        time.sleep(1)

monitor_website_changes()

我正在构建一个脚本,跟踪网站的变化,尽我最大的努力,以避免urlib库,因为我的困难理解它.如果可能的话,我想解决的问题坚持使用3库之前使用.

推荐答案

我猜当你第一次运行脚本时,文件不存在,所以你得到的错误.

我对这个问题进行了一点调整:

  1. 当运行时try 加载文件内容
  2. 如果没有找到文件,返回一个伪字符串
  3. 用这个字符串定期判断网站内容
  4. 如果有变化,保存页面到文件,更新字符串并转到步骤3.
import time

import requests


def get_prev_content(filename):
    try:
        with open(filename, "r", encoding="utf-8") as f_in:
            return f_in.read()
    except FileNotFoundError:
        return "dummy"


def monitor(filename, url):
    prev_content = get_prev_content(filename)
    while True:
        time.sleep(2)

        resp = requests.get(url)
        if prev_content == resp.text:
            print(".")
            continue

        print(f"{url=} changed, writing to {filename=} !")

        with open(filename, "w", encoding="utf-8") as f_out:
            f_out.write(resp.text)

        prev_content = resp.text


url = "https://news.ycombinator.com/"
filename = "website_content.txt"

monitor(filename, url)

打印:

...

.                
.                                              
url='https://news.ycombinator.com/' changed, writing to filename='website_content.txt' !
.

...

Python-3.x相关问答推荐

Pandas groupby基于索引的连续列值相等

Python gpsd客户端

PythonPandas 创建一个列并添加到DataFrame

根据另一列中的条件填写该列中的值

Strawberry FastAPI:如何调用正确的函数?

检测点坐标 - opencv findContours()

在新数据帧上自动提取两个字符串 python 之间的相等性

如何将 OLS 趋势线添加到使用 updatemenus 显示数据子集的 plotly 散点图图形对象?

有效地缩短列表,直到第一次和最后一次出现不同于 None 的值

Seaborn 热图 colored颜色 条标签作为百分比

TensorFlow:dataset.train.next_batch 是如何定义的?

tensorflow 中 numpy.newaxis 的替代方案是什么?

如何调试垂死的 Jupyter Python3 内核?

如何将numpy数组图像转换为字节?

接收导入错误:没有名为 *** 的模块,但有 __init__.py

Pyodbc:登录超时错误

没有名为urlparse的模块,但我没有使用 urlparse

如何为 Python 3.x 安装 psycopg2?

使用 python 3.0 的 Numpy

python中的绝对导入是什么?