检测并显示网页的更改

问题描述 投票:0回答:1

我正在尝试跟踪几个 URL,以了解它们何时进行更改(例如添加新文章),以及让脚本成为一个持续运行的程序,该程序将打印一条消息,表明某些内容已更改,如果可能,还显示已更改的内容。我最初有一个脚本调用 URL,对数据进行哈希处理,x 秒后重复该过程并比较哈希值是否发生变化,但是每当 URL 的较高级别发生任何更改时,我都会收到很多错误警报,而不仅仅是特定的子域。

我的问题是,有没有办法让 Beautiful soup 执行类似的操作,以便我知道何时添加文章,或者有没有办法修改我当前的脚本,仅通过利用除哈希比较。

我当前的脚本/尝试:

`# Importing libraries
import time
import hashlib
import logging
from urllib.request import urlopen, Request

logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S')

# setting the URL you want to monitor
url = Request('Input URL here',
            headers={'User-Agent': 'Mozilla/5.0'})

# to perform a GET request and load the
# content of the website and store it in a var
 response = urlopen(url).read()

# to create the initial hash
currentHash = hashlib.sha224(response).hexdigest()
print("running")
time.sleep(10)
while True:
    try:
        # perform the get request and store it in a var
        response = urlopen(url).read()

        # create a hash
        currentHash = hashlib.sha224(response).hexdigest()

        # wait for 30 seconds
        time.sleep(30)

        # perform the get request
        response = urlopen(url).read()

        # create a new hash
        newHash = hashlib.sha224(response).hexdigest()

        # check if new hash is same as the previous hash
        if newHash == currentHash:
            continue

        # if something changed in the hashes
        else:
            # notify
            logging.info("something changed in given URL")

            # again read the website
            response = urlopen(url).read()

            # create a hash
            currentHash = hashlib.sha224(response).hexdigest()

            # wait for 30 seconds
            time.sleep(30)
            continue

    # To handle exceptions
    except Exception as e:
        logging.info("error")`

自从我比较子域的哈希值以来,由于 URL 的高级域发生变化,我当前的脚本发出了许多错误警报。

python web-scraping beautifulsoup
1个回答
1
投票

我认为,您遇到的问题不是网址的更高级别发生了变化,而是您正在查看的页面在不断变化(例如添加时间戳等等)。

解决此问题的方法是查看自上次查看以来网页中的哪些行发生了更改。通过这种方式,您可以记下哪些行定期发生变化,并在寻找重大变化时忽略它们。

下面的代码每秒查看一个网页,并使用 difflib 打印出自上次查看以来已更改的行数列表。

import difflib
from urllib.request import urlopen, Request
import time

link = "https://website/"

url = Request(link, headers={'User-Agent': 'Mozilla/5.0'})
r_new = urlopen(url).read().decode('utf-8')
# print(r_new)

while True:
    time.sleep(1)
    r_old = r_new
    url = Request(link, headers={'User-Agent': 'Mozilla/5.0'})
    r_new = urlopen(url).read().decode('utf-8')

    diff = difflib.context_diff(r_new.splitlines(keepends=True),
                                r_old.splitlines(keepends=True), n=0)

    differences = []
    for line in diff:
        if (line.startswith('*** ') or line.startswith('--- ')) and len(line) > 5:
            differences.append(line.strip(' -*\n'))
    if not differences:
        differences = "No change"
    print(differences)

这是一个示例输出:

['470', '470', '575', '575']
['470', '470', '575', '575']
['470', '470', '575', '575']

因此,在这种情况下,第 470 行和第 575 行会随着每次读取而改变。如果这是您感兴趣的页面,那么您所需要做的就是在此列表中查找更改。

顺便说一句,不要忘记检查您网站的 robots.txt 文件以检查其对网络机器人的政策。

警告:此代码每秒都会访问网站,以便构建前几秒钟内的变化情况,并且只应运行几个周期。如此频繁地访问某个网站可能会导致该网站禁止您进一步访问。

© www.soinside.com 2019 - 2024. All rights reserved.