我正在设计一个Javascript API,我需要它来抓取特定远程HTML页面的内容。例如,我需要告诉它获取ID为“greeting”的元素的InnerHTML,并将其作为字符串发送给我。这可能与JS有关吗?如果没有,我是否需要使用Node.js或PHP?
答案 0 :(得分:0)
您是否尝试过使用selenium库来帮助您获取所需信息?
它主要用于进行UI自动化验证;如果您只是在本地使用它,它可以帮助您获得所需的信息:
答案 1 :(得分:0)
YQL可能就是您所需要的!
请参阅https://developer.yahoo.com/yql/
它允许您通过JSONP接口获取非本地数据。这意味着您将能够使用客户端javascript来抓取远程HTML。
Here is an example我从雅虎网站
获取<b>Stories: </b> <input type='text' size='15' id='story' value='world'/><br/><br/>
<button id='get_stories'>Get Stories</button>
<div id='results'></div>
<script src="https://yui-s.yahooapis.com/3.8.0/build/yui/yui-min.js"></script>
<script>
// Calls YQL Web service, parses results, and outputs results
YUI().use('node', 'event', 'yql', function(Y) {
Y.one("#get_stories").on('click',function() {
var stories = "<div><ul>";
var story = Y.one('#story').get('value') || 'world';
var news_url = "http://news.yahoo.com/";
var yql_query = "select * from html where url='" + news_url + story + "'";
yql_query += " and xpath='//div[@class=\"content\"]//div[@class=\"txt\"]/p'";
Y.YQL(yql_query, function(response) {
if(response.query.results){
var no_stories = response.query.results.p.length;
var paras = response.query.results.p;
paras.forEach(function(node,index) {
if (node.hasOwnProperty('a') && node.hasOwnProperty('content')) {
stories += "<li><a href='" + news_url + node.a.href + "' title='" + node.a.title + "'>" + node.content + "</a></li>";
}
});
} else{
stories += "Sorry, could not find any headlines for the category " + story + ". Please try another one.";
}
stories += "</ul></div>";
Y.one('#results').append(stories);
stories = "";
});
});
});
</script>