仅使用 Javascript 抓取特定的远程 HTML?

Scrape specific remote HTML with just Javascript?

我正在设计一个 Javascript API,我需要它来抓取特定远程 HTML 页面的内容。例如,我需要告诉它获取 ID 为 "greeting" 的元素的 InnerHTML 并将其作为字符串发回给我。这可能只用 JS 吗?如果不是,我需要使用 Node.js 还是 PHP?

您是否尝试过使用 selenium 库来帮助您获取所需的信息?

它主要用于 UI 自动化验证;如果您只是在本地使用,它可以帮助您获取所需的信息:

https://code.google.com/p/selenium/wiki/WebDriverJs

YQL 可能正是您所需要的!

https://developer.yahoo.com/yql/

它允许您通过 JSONP 接口获取非本地数据。这意味着您将能够仅通过客户端 javascript.

抓取远程 HTML

Here is an example我从yahoo的网站上拿的

<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>