正在从 url 获取元数据

Fetching metadata from url

我使用 Jsoup 库从 url 获取元数据。

Document doc = Jsoup.connect("http://www.google.com").get();  
String keywords = doc.select("meta[name=keywords]").first().attr("content");  
System.out.println("Meta keyword : " + keywords);  
String description = doc.select("meta[name=description]").get(0).attr("content");  
Elements images = doc.select("img[src~=(?i)\.(png|jpe?g|gif)]");  

String src = images.get(0).attr("src");
System.out.println("Meta description : " + description); 
System.out.println("Meta image URl : " + src);

但我想在 客户端 端使用 javascript

因为 cross-origin 问题,你不能做客户端。您需要一个服务器端脚本来获取页面的内容。

您可以使用YQL。这样,YQL 将用作代理。 https://policies.yahoo.com/us/en/yahoo/terms/product-atos/yql/index.htm

可以使用https://cors-anywhere.herokuapp.com。这样,cors-anywhere 将用作代理:

例如:

$('button').click(function() {
  $.ajax({
    url: 'https://cors-anywhere.herokuapp.com/' + $('input').val()
  }).then(function(data) {
    var html = $(data);

    $('#kw').html(getMetaContent(html, 'description') || 'no keywords found');
    $('#des').html(getMetaContent(html, 'keywords') || 'no description found');
    $('#img').html(html.find('img').attr('src') || 'no image found');
  });
});

function getMetaContent(html, name) {
  return html.filter(
  (index, tag) => tag && tag.name && tag.name == name).attr('content');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" placeholder="Type URL here" value="http://www.html5rocks.com/en/tutorials/cors/" />
<button>Get Meta Data</button>

<pre>
  <div>Meta Keyword: <div id="kw"></div></div>
  <div>Description: <div id="des"></div></div>
  <div>image: <div id="img"></div></div>
</pre>

纯Javascript函数

来自 node.js 后端 (Next.js) 我使用的是:

export const fetchMetadata = async (url) => {
    const html = await (await fetch(url, {
        timeout: 5000,
        headers: {
            'User-Agent': 'request'
        }
    })).text()
    
    var metadata = {};
    html.replace(/<meta.+(property|name)="(.*?)".+content="(.*?)".*\/>/igm, (m,p0, p1, p2)=>{ metadata[p1] = decode(p2) } );
    return metadata
}

export const decode = (str) => str.replace(/&#(\d+);/g, function(match, dec) {
    return String.fromCharCode(dec);
})

您可以在客户端使用 https://cors-anywhere.herokuapp.com/corsdemo