Javascript 用于密码保护网站的nodejs网页刮板
我正在尝试使用nodejs抓取一个网站,它在不需要任何身份验证的网站上完美地工作。但是,每当我尝试使用需要用户名和密码的表单刮取站点时,我只从身份验证页面获取HTML(也就是说,如果您自己在身份验证页面上单击“查看页面源代码”,这就是我获取的HTML)。我能够使用curl获得所需的HTMLJavascript 用于密码保护网站的nodejs网页刮板,javascript,node.js,authentication,web-scraping,scrape,Javascript,Node.js,Authentication,Web Scraping,Scrape,我正在尝试使用nodejs抓取一个网站,它在不需要任何身份验证的网站上完美地工作。但是,每当我尝试使用需要用户名和密码的表单刮取站点时,我只从身份验证页面获取HTML(也就是说,如果您自己在身份验证页面上单击“查看页面源代码”,这就是我获取的HTML)。我能够使用curl获得所需的HTML curl -d "username=myuser&password=mypw&submit=Login" URL 这是我的密码 var express = require('express'
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
request({form: {username:myuser, password:mypw, submit:Login}, url: myURL}, function(error, response, html){
...
...
...
}
因此,我的问题是如何使用nodejs实现这一点?您不应该使用.get but.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中使用了上述代码,但我收到一个错误“对不起,您的会话已过期。请刷新并重试”。请建议。