【问题标题】:nodejs web scraper for password protected website用于受密码保护的网站的 nodejs 网络爬虫
【发布时间】:2014-12-23 14:03:47
【问题描述】:

我正在尝试使用 nodejs 抓取一个网站,它可以在不需要任何身份验证的网站上完美运行。但是,每当我尝试使用需要用户名和密码的表单来抓取网站时,我只能从身份验证页面获取 HTML(也就是说,如果您在身份验证页面上单击“查看页面源代码”它自己,那就是我的 HTML得到)。我可以使用 curl 获得所需的 HTML

curl -d "username=myuser&password=mypw&submit=Login" URL

这是我的代码...

var express = require('express');
var fs = require('fs'); //access to file system
var request = require('request');
var cheerio = require('cheerio');
var app     = express();

app.get('/scrape', function(req, res){
url = 'myURL'

request(url, function(error, response, html){

    // check errors
    if(!error){
        // Next, we'll utilize the cheerio library on the returned html which will essentially give us jQuery functionality
        var $ = cheerio.load(html);

        var title, release, rating;
        var json = { title : "", release : "", rating : ""};

        $('.span8 b').filter(function(){
            // Let's store the data we filter into a variable so we can easily see what's going on.
            var data = $(this);
            title = data.first().text();
            release = data.text();

            json.title = title;
            json.release = release;
        })
    }
    else{
        console.log("Error occurred: " + error);
    }

    fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err){

        console.log('File successfully written! - Check your project directory for the output.json file');

    })

    res.send('Check your console!')
})

})

app.listen('8081')
console.log('Magic happens on port 8081');
exports = module.exports = app;

我已经尝试了以下...

var request = require('request',
    username:'myuser',
    password:'mypw');

这只是返回认证页面的 HTML

request({form: {username:myuser, password:mypw, submit:Login}, url: myURL}, function(error, response, html){
    ...
    ...
    ...
}

这也只是返回认证页面的 HTML

所以我的问题是如何使用 nodejs 实现这一点?

【问题讨论】:

    标签: javascript node.js authentication web-scraping scrape


    【解决方案1】:

    你不应该使用 .get 而应该使用 .post 并将 post 参数(用户名和密码)放在你的调用中

    request.post({
      headers: {'content-type' : 'application/x-www-form-urlencoded'},
      url:     url,
      body:    "username=myuser&password=mypw&submit=Login"
    }, function(error, response, html){
        //do your parsing... 
        var $ = cheerio.load(html)
    });
    

    【讨论】:

    • 我在 node js 中使用了上面的代码,但我收到一个错误“对不起,您的会话已过期。请刷新并重试”。请提出建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多