API instead of BeautifulSoup?



这个文档定义了一些MS服务的URL和IP:https://learn.microsoft.com/en-us/microsoft-365/enterprise/urls-and-ip-address-ranges?view=o365-worldwide exchange-online

我的目标是写一个Python脚本来检查这个文档的最后更新日期。如果日期有变化(意味着一些IP发生了变化),我需要马上知道。我找不到任何API来实现这个目标,所以我写了这个脚本:

from bs4 import BeautifulSoup
import requests
import time
import re
url = "https://learn.microsoft.com/en-us/microsoft-365/enterprise/urls-and-ip-address-ranges?view=o365-worldwide#exchange-online"
#set the headers as a browser
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
while True:
response = requests.get(url,headers=headers)
soup = BeautifulSoup(response.text,"html.parser")
last_update_fra = soup.find(string=re.compile("01/04/2021"))
time.sleep(60)
soup = BeautifulSoup(requests.get(url, headers=headers).text, "html.parser")
if soup.find(string=re.compile("01/04/2021")) == last_update_fra:
print(last_update_fra)
continue
else:
#send an email for notification
pass

我不确定这是不是最好的方法。因为如果日期会改变,我还需要更新我的脚本到另一个日期(更新的日期)。另外,用BeautifulSoup也可以吗?或者还有更好的办法?

Beautifulsoup在这里很好。我甚至没有看到带有数据的XHR请求。

注意事项:

  1. 你真的需要每分钟检查一次吗?也许每天/24小时更好,或者12或6小时更好?
  2. 如果在任何时候它崩溃了,即你失去了互联网连接或得到一个400响应,你需要重新启动脚本,失去最后的日期是什么。所以也许可以考虑a)将日期写到磁盘的某个地方,这样它就不只是存储在内存中,b)在那里放一些try/exceptions,这样如果它遇到错误,它会继续运行,只是在下一个间隔再试一次(或者你决定如何再试一次)。

代码:

import requests
import time
from bs4 import BeautifulSoup
url = 'https://learn.microsoft.com/en-us/microsoft-365/enterprise/urls-and-ip-address-ranges?view=o365-worldwide#exchange-online'
#set the headers as a browser
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
last_update_fra = ''
while True:
time.sleep(60)
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
found_date = soup.find('time').text
if found_date == last_update_fra:    
print(last_update_fra)
continue
else:
# store new date
last_update_fra = found_date

#send an email for notification
pass

最新更新