我刚刚开始使用java脚本,我想从URL中获取元数据...当在输入字段中输入任何URL时,它必须从中提取元数据,这是执行时在html java脚本中使用的基本用法代码抛出错误
我正在寻找任何替代方案,但没有任何帮助。请提供如何实现该功能的任何想法。
<!DOCTYPE html>
<html>
<body>
<head>
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML5,CSS,JavaScript">
<meta name="author" content="John Doe">
<meta content="http://stackoverflow.com/favicon.ico">
</head>
<p>Click the button to return the value of the content attribute of all meta elements.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = "https://www.amazon.in/"
// var x = document.getElementsByTagName("META");
var txt = "";
var i;
for (i = 0; i < x.length; i++) {
txt = txt + "Content of "+(i+1)+". meta tag: "+x[i].content+"<br>";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
小智 5
我猜你正在尝试使用 javascript 构建元数据抓取器,如果没有错的话。
在从任何 url 请求数据时,您需要先考虑 CORS 策略,然后再继续操作。
参考网址:
JSFiddle:http://jsfiddle.net/pgrmL73h/
已经演示了如何从给定的 URL 中获取元标记。出于演示目的,我使用https://jsfiddle.net/ url 来获取元标记,您可以根据需要更改它。
按照以下步骤从网站检索 META 标签。
要从任何网站 URL 检索页面源,首先您需要访问该网站。使用 jquery AJAX 方法你可以做到这一点。
参考网址: https: //api.jquery.com/jquery.ajax/
使用 jQuery 中的 $.parseHTML 方法,该方法有助于从 html 字符串中检索 DOM 元素。
参考网址: https: //api.jquery.com/jquery.parsehtml/
一旦 AJAX 请求成功检索页面源,我们就会检查页面源中的每个 DOM 元素,并根据我们的需要过滤 META 节点,并将数据存储在“txt”变量中。
EG:将检索关键字、描述等标签。
JS代码:
function myFunction() {
var txt = "";
document.getElementById("demo").innerHTML = txt;
// sample url used here, you can make it more dynamic as per your need.
// used AJAX here to just hit the url & get the page source from those website. It's used here like the way CURL or file_get_contents (https://www.php.net/manual/en/function.file-get-contents.php) from PHP used to get the page source.
$.ajax({
url: "https://jsfiddle.net/",
error: function() {
txt = "Unable to retrieve webpage source HTML";
},
success: function(response){
// will get the output here in string format
// used $.parseHTML to get DOM elements from the retrieved HTML string. Reference: https://api.jquery.com/jquery.parsehtml/
response = $.parseHTML(response);
$.each(response, function(i, el){
if(el.nodeName.toString().toLowerCase() == 'meta' && $(el).attr("name") != null && typeof $(el).attr("name") != "undefined"){
txt += $(el).attr("name") +"="+ ($(el).attr("content")?$(el).attr("content"):($(el).attr("value")?$(el).attr("value"):"")) +"<br>";
console.log($(el).attr("name") ,"=", ($(el).attr("content")?$(el).attr("content"):($(el).attr("value")?$(el).attr("value"):"")), el);
}
});
},
complete: function(){
document.getElementById("demo").innerHTML = txt;
}
});
}
Run Code Online (Sandbox Code Playgroud)