簡體   English   中英

如何從HTML中提取JavaScript

[英]How do I extract javascript from within html

我正在使用request和cheerio創建一個用javascript編寫的網絡抓取程序。 我嘗試提取的網頁在html中包含javascript。 這是我感興趣的javascript,但是找不到訪問它的方法。 有沒有一種使用cheerio提取javascript的方法?

非常感謝您的任何建議,我剛剛開始進行網絡抓取。

我的代碼是:

var request = require('request');
var cheerio = require('cheerio');

var credentials = {
    username: 'username',
    password: 'password'
};

request.post({
    uri: 'http://webpage',
    headers: { 'content-type': 'application/x-www-form-urlencoded' },
    body: require('querystring').stringify(credentials)
}, function(err, res, body){
if(err) {
    callback.call(null, new Error('Login failed'));
    return;
}

request('http://webpage', function(err, res, body)
{
    if(err) {
        callback.call(null, new
            Error('Request failed'));
        return;
    }

    var $ = cheerio.load(body);
    var text = $('#element').text();
    console.log($.html());

}); 

});

如果要在網頁中查找javascript,則可以使用cheerio從html收集所有<script>標記,然后從中獲取內容。

var scripts = [];

request('http://webpage', function(err, res, body)
{
  if(err) {
    callback.call(null, new Error('Request failed'));
    return;
  }

  var $ = cheerio.load(body);
  $('script').each(function(i, element) {
    scripts[i] = $(element).text();
  }   
});

現在,您將擁有一個數組,其中包含HTML中所有可用的javascript。 現在,如果它們是導入的javascript,那么您將不會獲得任何內容。 您可以搜索該元素是否具有src url。

...

$('script').each(function(i, element) {
  if ($(element).attr('src') === undefined) {
    scripts[i] = $(element).text();
  }
  else {
    // Collect or ignore this.
  }
}

...

我尚未對此進行測試,但是它應該根據cheerio的文檔進行工作。

https://github.com/cheeriojs/cheerio

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM