用于受密码保护的网站的nodejs Web抓取工具 [英] nodejs web scraper for password protected website
问题描述
我正在尝试使用nodejs抓取一个网站,并且该网站在不需要任何身份验证的网站上可以完美运行.但是,每当我尝试使用要求用户名和密码的表单来抓取网站时,我只会从身份验证页面获取HTML(也就是说,如果您单击身份验证页面上的查看页面源",它本身就是HTML)得到).我可以使用curl获得所需的HTML
I am trying to scrape a website using nodejs and it works perfectly on sites that do not require any authentication. But whenever I try to scrape a site with a form that requires username and password I only get the HTML from the authentication page (that is, if you would click 'view page source' on the authentication page it self, that is the HTML I get). I am able to get the desired HTML using curl
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;
我尝试了以下方法...
I have tried the following...
var request = require('request',
username:'myuser',
password:'mypw');
这只是返回身份验证页面的HTML
This just returns the authentication page's HTML
request({form: {username:myuser, password:mypw, submit:Login}, url: myURL}, function(error, response, html){
...
...
...
}
这也只返回身份验证页面的HTML
This also just returns the authentication page's HTML
所以我的问题是如何使用nodejs实现这一目标?
So my question is how do I achieve this using nodejs?
推荐答案
您不应使用.get而是.post并在通话中添加post参数(用户名和密码)
you shouldn't use .get but .post and put the post param (username and password) in your call
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)
});
这篇关于用于受密码保护的网站的nodejs Web抓取工具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!