2016-03-27 10 views
2

私は、リモートWebサイトのDOMを取得して解析することができます。つまり、解析結果をDOMノードに変換し、必要な要素を効果的に取得して後で処理することが理想です。つまり、検索されたDOMから特定の要素をスライスし、その後の操作のために配列に格納したいと思います。それは実際に達成可能ですか?このコードは、私の見解にリモートページのDOMを取得しますが、結果が戻っとして来JS内のリモートDOMを解析する

import express from 'express'; 
import getBody from '../server'; 

const router = express.Router(); 

const url = 'http://www.google.com'; 
let result = {}; 

getBody(url, response => { 
    result = response; 
}); 

router.get('/', (req, res, next) => { 
    res.render('index', { title: 'Express', data: result }); 
}); 

export default router; 

import request from 'request'; 

export default function getBody(url, callback) { 
    request(url, (err, res, body) => { 
    callback(body); 
    }); 
} 

とルートフォルダ内: は、これまでのところ、私はこれで来ています巨大な弦であり、それを扱うのは悪夢になるだろう。私はフロントエンドからそれを処理するためにbrowser-requestライブラリを使用しようとしましたが、ヘッダが機能しなくなり、常にエラーが返されます。No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

リモートを取得するための最善の方法は? DOMと上記の方法でそれを解析する?

答えて

3

jQueryに精通している場合は、cheerioを使用してDOMを通過できます。

import request from 'request'; 
import cheerio from 'cheerio'; 

export default function getBody(url, callback) { 
    request(url, (err, res, body) => { 
    $ = cheerio.load(body); 
    $('h2') // finds all of the `h2` tags within the `body` object. 
    }); 
} 
+0

私が必要としただけの魅力のように働いた。 –