使用jQuery进行简单的屏幕刮擦 [英] Simple Screen Scraping using jQuery

查看:172
本文介绍了使用jQuery进行简单的屏幕刮擦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用使用jQuery的简单屏幕抓取器的想法,我想知道以下是否可行。

I have been playing with the idea of using a simple screen-scraper using jQuery and I am wondering if the following is possible.

我有简单的HTML页面和我正在尝试(如果可能的话)从另一个页面中获取所有列表项的内容,如下所示:

I have simple HTML page and am making an attempt (if this is possible) to grab the contents of all of the list items from another page, like so:

主页:

<!-- 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服务器代理该文件。

Use $.ajax to load the other page into a variable, then create a temporary element and use .html() to set the contents to the value returned. Loop through the element's children of nodeType 1 and keep their first children's nodeValues. If the external page is not on your web server you will need to proxy the file with your own web server.

这样的事情:

$.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
          }
     }
});

这篇关于使用jQuery进行简单的屏幕刮擦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆