使用jQuery进行简单的屏幕抓取

|| 我一直在考虑使用jQuery使用简单的屏幕抓取工具的想法,我想知道是否可以进行以下操作。 我有一个简单的HTML页面,正在尝试(如果可能的话)从另一个页面获取所有列表项的内容,例如: 主页:
<!-- jQuery -->
<script type=\'text/javascript\'>
$(document).ready(function(){
$.getJSON(\"[URL to other page]\",
  function(data){

    //Iterate through the <li> inside of the URL\'s data
    $.each(data.items, function(item){
      $(\"<li/>\").value().appendTo(\"#data\");
    });

  });
});
</script>

<!-- HTML -->
<html>
    <body>
       <div id=\'data\'></div>
    </body>
</html>
其他页面:
//Html
<body>
    <p><b>Items to Scrape</b></p>   
    <ul>
        <li>I want to scrape what is here</li>
        <li>and what is here</li>
        <li>and here as well</li>
        <li>and append it in the main page</li>
    </ul>
</body>
因此,是否有可能使用jQuery从外部页面提取所有列表项内容并将其附加到div中?     
已邀请:
使用
$.ajax
将另一页加载到变量中,然后创建一个临时元素,然后使用
.html()
将内容设置为返回的值。循环遍历nodeType 1的元素的子节点,并保留其第一个子节点的nodeValues。如果外部页面不在您的Web服务器上,则需要使用您自己的Web服务器代理该文件。 像这样:
$.ajax({
     url: \"/thePageToScrape.html\",
     dataType: \'text\',
     success: function(data) {
          var elements = $(\"<div>\").html(data)[0].getElementsByTagName(\"ul\")[0].getElementsByTagName(\"li\");
          for(var i = 0; i < elements.length; i++) {
               var theText = elements[i].firstChild.nodeValue;
               // Do something here
          }
     }
});
    
$.get(\"/path/to/other/page\",function(data){
  $(\'#data\').append($(\'li\',data));
}
    
如果这是针对同一域的,那么没有问题-jQuery解决方案很好。 但是,否则您将无法从任意网站访问内容,因为这被认为存在安全风险。请参阅相同的原产地政策。 当然,还有服务器端的解决方法,例如Web代理或CORS标头。 如果您很幸运,它们将支持jsonp。 但是,如果您想让客户端解决方案与任意网站和Web浏览器一起使用,那么您就不走运了。有人提议放宽此政策,但这不会影响当前的Web浏览器。     
您可能需要考虑使用pjscrape: http://nrabinowitz.github.io/pjscrape/ 它允许您使用javascript和jQuery从命令行执行此操作。它使用PhantomJS(无头Webkit浏览器)完成此操作(它没有窗口,并且仅用于脚本用途,因此您可以加载使用AJAX的复杂网站,并且可以像使用AJAX一样工作真正的浏览器)。 这些示例是不言自明的,我相信这适用于所有平台(包括Windows)。     
用jQuery简单抓取...
// Get HTML from page
$.get( \'http://example.com/\', function( html ) {

    // Loop through elements you want to scrape content from
    $(html).find(\"ul\").find(\"li\").each( function(){

        var text = $(this).text();
        // Do something with content

    } )

} );
    
使用YQL或Yahoo管道对原始页面html内容进行跨域请求。 yahoo管道或YQL查询会将其作为JSON吐回来,可以由jquery处理以提取并显示所需的数据。 缺点:YQL和Yahoo用管道传递目标域的robots.txt文件 如果页面太长,则Yahoo Pipes regex命令将不会运行。     
我相信您会在许多情况下遇到CORS问题。 从这里尝试解决CORS问题。
var name = \"kk\";
var url = \"http://anyorigin.com/go?url=\" + encodeURIComponent(\"https://www.yoursite.xyz/\") + name + \"&callback=?\";
$.get(url, function(response) {
  console.log(response);
});
    

要回复问题请先登录注册