我想编写一个脚本,通过网址列表查看它们是否有效。
页面不会重定向到404,而是显示句子'抱歉,找不到!如果URL无效。
因此,如果脚本找到此句子,则该URL无效。如果没有,它很可能是有效的。
如何在JS中实现这一点?也欢迎使用其他语言的可能方法的指针!
谢谢!
答案 0 :(得分:0)
一种简单的Python方式是:
import requests
urls = ['https://www.google.com'] # Fill this however
for url in urls:
resp = requests.get(url)
if 'Sorry, not found!' in resp.text:
print(url + ' had no page') # or something
答案 1 :(得分:0)
我用 jQuery 成功了。我不认为任何人都可以单独使用javascript。无论如何你都必须使用jQuery。
首先,您应该在Chrome控制台中试用:
1.添加此扩展程序以消除CORS策略错误 Chrome Extension。确保在Chrome->更多工具 - >扩展程序
中启用它2.现在我们必须运行get(),我们不能像通常在.js文件中使用的$ .get()那样调用它。因此我们需要通过在控制台中运行以下行来将其转换为控制台:
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
3.Fire get request:
var rsp = jQuery.get("https://www.google.com/");
等待2秒......(ES6已禁用同步请求,因此请等待rsp填充)
if (rsp.responseText && rsp.responseText.includes("was not found")) { //In your js file replace with Sorry! not found
console.log("The Url is Invalid");
}
else {
console.log("could be a valid url"); //this must get printed
}
尝试无效网址:
var rsp = jQuery.get("https://www.goesfsfsfsffogle.com/");
等待2秒......
if (rsp.responseText && rsp.responseText.includes("was not found")) { //In your js file replace with Sorry! not found
console.log("The Url is Invalid"); //this must get printed
}
else {
console.log("could be a valid url");
}
在jQuery项目文件中运行:
var urls = ["https://www.google.com/"];
var url;
for ( url in urls ){
var rsp = $.get(url);
//A wait should be added here for rsp to get populated
//console.log("readyState="+rsp.readyState);
if (rsp.responseText && rsp.responseText.includes("Sorry! not found"))
{
console.log("The Url is Invalid");
}
else {
console.log("Its a valid url");
}
}
再次,如果rsp不包含readyState === 4,则表示尚未收到异步响应。如果在这种情况下检查,我们需要添加等待。
如果这对您没有帮助,请告诉我。