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

2024-10-01 09:40:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个机器人,检查是否有任何变化,在一个给定的网站,因为上次被刮。为此,它会抓取网站,将其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,从而触发脚本


Tags: 文件importtxt脚本url网站htmlas
1条回答
网友
1楼 · 发布于 2024-10-01 09:40:25

您需要通过设置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)

相关问题 更多 >