如何通过目标站点上的websockets抓取流式传输的JSON数据

时间:2013-11-08 19:11:19

标签: php websocket socket.io web-scraping

我被要求刮一个通过websockets接收数据的网站,然后通过javascript / jquery将其呈现给页面。是否有可能绕过中间人(DOM)并消耗/刮取来自套接字的数据?这可能是像phantomJS这样的无头webkit吗?目标网站正在使用socket.io

我需要根据数据中的关键字使用数据并触发警报。我正在考虑Goutte库,并将用PHP构建刮刀。

2 个答案:

答案 0 :(得分:6)

Socket.io与websockets不完全相同。既然你知道他们使用socket.io我就是专注于那个。 刮掉这个套接字的最简单方法是使用socket.io客户端。

将它放在您的页面上:

<script src="https://github.com/LearnBoost/socket.io-client/blob/0.9/dist/socket.io.js"></script>
<script src="scraper.js"></script>

创建文件scraper.js:

var keywords = /foo|bar/ig;
var socket = io.connect('http://host-to-scrape:portnumber/path');
socket.on('<socket.io-eventname>', function (data) {
  // The scraped data is in 'data', do whatever you want with it
  console.log(data);

  // Assuming data.body contains a string containing keywords:
  if(keywords.test(data.body)) callOtherFunction(data.body);

  // Talk back:
  // socket.emit('eventname', { my: 'data' });
});

更新6-1-2014

而不是在服务器上运行它,看起来您试图在浏览器窗口中运行它,查看下面引用的StackOverflow问题。所以我删除了有关NodeJS的所有内容,因为不需要。

答案 1 :(得分:-2)

在我看来,这对你来说是最好的方式:

使用javascript直接从应用程序的客户端页面中删除数据,而不使用php作为中端。通过这种方式,您的服务器将没有绝对任何负载,我会推荐这个。由于您的目标站点使用的是socket.io,请使用socket.io客户端来废弃数据。表格socke.io offiscial site

    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io.connect('http://target_website.com');
              //look the next line closely
      socket.on('event_name', function (data) {
        console.log(data);
        //do something with data here
      });
    </script>

问题出现时,您如何知道 * event_name * ?你必须通过对目标网站的js进行研究来找到它。没有工作。至少我不知道他们中没有他们。