【发布时间】:2017-06-27 07:46:29
【问题描述】:
在我的应用程序中,我将使用Yahoo YQL 的htmlstring 从xml 或json 输出的网站中提取html。
我这样做的原因是为了得到它的property="og:image"、property="og:title" 和property="og:image"。
目前我正在这样做:
XML 输出:
$(function () {
var query;
var apiUrl;
$("button.click").click(function () {
apiUrl = "https://query.yahooapis.com/v1/public/yql?q=select * from htmlstring where url='http://stackoverflow.com/'&diagnostics=true&env=store://datatables.org/alltableswithkeys";
$('p.extract').toggle();
$.get(apiUrl, function(data) {
$('p.extract').addClass('none');
var html = $(data).find('html');
$("input.title" ).val(html.find("meta[property='og:title']").attr('content') || 'no description found');
$("textarea.description").val(html.find("meta[property='og:description']").attr('content') || 'no title found');
$("input.image").val(html.find("meta[property='og:image']").attr('content') || 'no image found');
});
});
});
input {
width: 100%;
margin-bottom: 20px;
padding: 10px;
}
.none{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button class="click">Click Me</button>
<br>
<p class="extract" style="display:none;">Extracting html</p>
<input type="text" class="title">
<br>
<textarea name="" id="" cols="30" rows="5" class="description"></textarea>
<br>
<input type="text" class="image">
JSON 输出:
$(function () {
var apiUrl;
$("button.click").click(function () {
apiUrl = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D%22http%3A%2F%2Fstackoverflow.com%2F%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
$('p.extract').toggle();
$.get(apiUrl, function(data) {
$('p.extract').addClass('none');
var html = $(data).find('html');
$("input.title" ).val(html.find("meta[property='og:title']").attr('content') || 'no description found');
$("textarea.description").val(html.find("meta[property='og:description']").attr('content') || 'no title found');
$("input.image").val(html.find("meta[property='og:image']").attr('content') || 'no image found');
});
});
});
input {
width: 100%;
margin-bottom: 20px;
padding: 10px;
}
.none{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="click">Click Me</button>
<br>
<p class="extract" style="display:none;">Extracting html</p>
<input type="text" class="title">
<br>
<textarea name="" id="" cols="30" rows="5" class="description"></textarea>
<br>
<input type="text" class="image">
我目前所做的并没有提供我想要的详细信息,即使我可以在输出中看到它们,我也找不到任何东西。
感谢任何帮助,因为我不知道自己做错了什么。
【问题讨论】:
-
您可以将
data.results.result转换为“可能是JSON”的对象吗?我感觉你在刮一根绳子……
标签: jquery html ajax yql yahoo-api