写一个PYthon 能检查指定txt文件里面链接打开后是否和txt文件链接一致的完整代码
以下是一个Python程序,可以读取指定的txt文件,检查每个链接,然后检查它们是否与txt文件中给出的链接一致。
import requests
import re
# 定义一个函数,用于检查链接是否有效
def check_link(url):
try:
response = requests.head(url)
status_code = response.status_code
if status_code >= 200 and status_code < 400:
return True
else:
return False
except:
return False
# 读取txt文件
filename = input("请输入txt文件名:")
with open(filename, "r") as file:
content = file.read()
# 使用正则表达式获取所有链接
links = re.findall("(?P<url>https?://[^\s]+)", content)
# 检查链接是否与txt文件中给出的链接一致
for link in links:
if check_link(link):
print(link + " 是有效链接")
else:
print(link + " 是无效链接")
该程序首先要求用户输入txt文件名,然后打开文件并读取其内容。使用正则表达式,程序会查找文件中的所有链接,并将它们存储在一个列表中。然后,程序循环遍历该列表,并使用check_link函数检查每个链接是否有效。如果链接有效,则程序输出“是有效链接”;否则,它会输出“是无效链接”
原文地址: https://www.cveoy.top/t/topic/hvIv 著作权归作者所有。请勿转载和采集!