从 URL 中获取元数据

8
我使用Jsoup库从网址中提取元数据。
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在客户端上完成它

3个回答

21
由于跨域问题,您无法仅使用客户端进行操作。您需要使用服务器端脚本来获取页面内容。 或者您可以使用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>


谢谢您提供的解决方案,但我该如何从URL中显示图像呢? 附注:URL包含许多图像,如何显示其中最好的一个。 - SR230
最好的一个是哪个?你怎么知道谁是最好的? - Mosh Feu
这是一个稳定的解决方案,可用于在社交网络中从URL中抓取元数据,就像Facebook一样吗?它能处理许多并发请求吗? - Engineeroholic
@Engineeroholic 我没有用很多请求来测试它。我相信Facebook不会这样做。 "正确"的解决方案是使用"代理"服务器。更多信息请阅读答案。 - Mosh Feu
1
你想获取的URL是什么? - Mosh Feu
显示剩余3条评论

0

纯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


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接