Python scraper总是发现网站的上一个版本和当前版本之间存在差异,而没有差异

Python scraper总是发现网站的上一个版本和当前版本之间存在差异,而没有差异,python,python-requests,Python,Python Requests,我正在写一个机器人,它会检查给定网站自上次被删除以来是否有任何变化。为此,它会抓取网站,将其html代码存储在本地文件中,然后一遍又一遍地抓取,如果新旧版本之间存在差异,它会覆盖本地文件并打印。问题是,我的脚本总是发现差异并覆盖文件,即使没有更改 可复制示例: import requests import time import os def compare(file, url): if os.path.isfile("./" + file): scrape = req

我正在写一个机器人,它会检查给定网站自上次被删除以来是否有任何变化。为此,它会抓取网站,将其html代码存储在本地文件中,然后一遍又一遍地抓取,如果新旧版本之间存在差异,它会覆盖本地文件并打印。问题是,我的脚本总是发现差异并覆盖文件,即使没有更改

可复制示例:

import requests
import time
import os

def compare(file, url):
    if os.path.isfile("./" + file):
        scrape = requests.get(url).text
        with open(file) as f:
            txt=f.read()
        if not txt == scrape:
            with open(file, "w") as f:
                f.write(scrape)
            print("Triggered")
    else:
        scrape=requests.get(url).text
        with open(file, "w") as f:
            f.write(scrape)

ceu = "https://hro.ceu.edu/find-job"
ceu_file = "ceu.html"

while True:
    compare(ceu, ceu_file)
    time.sleep(10)

所以,问题是脚本每次抓取网站时都会被触发,即使网站不会每10秒更改一次。为什么函数中的txt==scrape始终为false,从而触发脚本?

您需要通过设置newline=禁用自动换行转换,以防止在写入文件时换行转换为系统默认值:

import requests
import time
import os

def compare(url, file_):
    if os.path.isfile("./" + file_):
        scrape = requests.get(url).text
        with open(file_, "r", newline='') as f:
            txt = f.read()
        if txt != scrape:
            with open(file_, "w", newline='') as f:
                f.write(scrape)
            print("Triggered")
        else:
            print('Not triggered')
    else:
        scrape = requests.get(url).text
        with open(file_, "w", newline='') as f:
            f.write(scrape)

ceu = "https://hro.ceu.edu/find-job"
ceu_file = "ceu.html"

while True:
    compare(ceu, ceu_file)
    time.sleep(10)

那么,您是否尝试打印以前和当前的内容以查看差异所在?看起来它正在覆盖else块中的文件,即使txt==scrape-这是有意的?尝试的一件事是实际比较您编写的内容和您尝试编写的内容。在某些平台上,像换行符这样的东西发送的方式不同,你需要进行二进制读/写来区分不同之处。我改正了。但它仍然无法解决问题。Kevin-我刚刚删除了这两个文件中的\r,并使用了以下内容:output_list=[li for li in difflib.ndifftxt,scrape if li[0]!=']-查找txt和scrape之间的差异。输出完全是随机的,我看不到任何差异模式-['+e'、'+V'、'+z'、'+n'、'+2'、'+j'、'+F'、'+F'、'+F'、'+X'、'+V'、'+2'、'+F'、'-8'、'-U'、'-p'、'+l'、'+1'、'+3'、'+W'、'+X'、'+M'、'+I'、'+n'、'+z'.]。似乎这种方法在概念上有问题……谢谢!它不再为这个特定的网站触发,但它仍然会为其他一些网站触发,如。所以,这确实是问题的一部分,但不是整个问题。@AlexeyGridnov不,这是您提供的代码的唯一问题。对于其他代码/网站,分析写作前后的差异,你会发现新的problem@AlexeyGridnev只是为了好玩,我检查了差异。站点每次动态地为div生成一个新id。这在网站上创造了一个真正的差异,但是我认为你实际上并不关心这个差异。