Commit 53dce1f2 by 马玮

add error handle class

parent 9787170f
......@@ -7,7 +7,7 @@ const path = require('path');
const program = require('commander');
const config = require('config');
const captcha = require('./lib/captcha');
const dealerSpider = require('./lib/dealerspider/index');
const DealerSpider = require('./lib/dealerspider/index');
program
.version('0.1.0')
......@@ -16,10 +16,11 @@ program
.parse(process.argv);
// console.log(process.pid);
let dealerWebInfo = config.get('Dealer')[program.webname];
let spider = new dealerSpider({
const dealerWebInfo = config.get('Dealer')[program.webname];
const spider = new DealerSpider({
username : dealerWebInfo.username,
password : dealerWebInfo.password,
webname : program.webname,
task : program.task
}).execute();
\ No newline at end of file
});
spider.execute();
\ No newline at end of file

4.93 KB | W: | H:

4.78 KB | W: | H:

captcha1.png
captcha1.png
captcha1.png
captcha1.png
  • 2-up
  • Swipe
  • Onion skin

4.93 KB | W: | H:

4.78 KB | W: | H:

captcha2.png
captcha2.png
captcha2.png
captcha2.png
  • 2-up
  • Swipe
  • Onion skin
......@@ -5,6 +5,8 @@ const fs = require('fs');
const config = require('config');
const axios = require('axios');
const FormData = require('form-data');
const errors = require('../errors');
const ruokuai = exports;
ruokuai.decode = async function (typeid, imageFile) {
......@@ -31,7 +33,8 @@ ruokuai.decode = async function (typeid, imageFile) {
if (response.data.Result) {
return response.data.Result;
} else {
throw JSON.stringify(response.data);
let message = (response.data.Error || '验证码解析错误') + ': 若快code: ' + (response.data.Error_Code || '');
throw new errors.CaptchaDecodeError(message);
}
} catch (e) {
throw e;
......
......@@ -15,11 +15,11 @@ const axios = require('axios');
const axiosCookieJarSupport = require('@3846masa/axios-cookiejar-support');
// 自定义模块
const captcha = require('../captcha');
const errors = require('../errors');
Promise.promisifyAll(redis);
Promise.promisifyAll(fs);
axios.defaults.withCredentials = true;
axiosCookieJarSupport(axios);
class AutoHome {
constructor(params) {
......@@ -62,32 +62,30 @@ class AutoHome {
async tryLogin() {
try {
let cookies = await this.getCookies();
let loginSuccess = false;
const horseman = new Horseman();
const loginoutBtnExists = await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.cookies(cookies)
.open('http://ics.autohome.com.cn/passport/Home/Index')
.screenshot('try.png')
.exists('#loginout');
if (cookies) {
const horseman = new Horseman({
ignoreSSLErrors: true
});
if (loginoutBtnExists) {
this.login.status = 'success';
this.login.message =
} else {
this.login.status = 'error';
loginSuccess =
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.cookies(cookies)
.open('http://ics.autohome.com.cn/passport/Home/Index')
.screenshot('try.png')
.exists('#loginout');
await horseman.close();
}
this.login.message = loginoutBtnExists ? '登录成功' : '尝试登录失败';
await horseman.close();
return loginoutBtnExists;
// await horseman
// .open('http://ics.autohome.com.cn/BSS/MyMch/PersonalInfo')
// .screenshot('try2.png').close();
// ;
if (loginSuccess) {
return 'success';
} else {
throw new errors.TryLoginError('尝试登录失败');
}
} catch (e) {
throw e;
}
......@@ -95,12 +93,22 @@ class AutoHome {
async login() {
try {
await this.tryLogin();
try {
await this.tryLogin();
console.log('登录成功');
return;
} catch (e) {
console.log(e.message);
}
console.log('成功就不走这');
const username = this.params.username;
const password = this.params.password;
const horseman = new Horseman();
const horseman = new Horseman({
ignoreSSLErrors: true
});
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
......@@ -109,6 +117,7 @@ class AutoHome {
horseman.on('onResourceRequested', (requestData, networkRequest) => {
console.info('Requesting', requestData.url);
console.log('networkRequest', networkRequest);
});
// 验证码存储到磁盘
......@@ -128,9 +137,15 @@ class AutoHome {
});
// 验证码解码
const captchaType = config.get('Dealer')[this.params.webname]['captchaType'];
const captchaText = await captcha.decode(captchaType, imageFile);
console.info('captchaText:', captchaText);
let captchaText;
try {
const captchaType = config.get('Dealer')[this.params.webname]['captchaType'];
captchaText = await captcha.decode(captchaType, imageFile);
console.info('captchaText:', captchaText);
} catch (e) {
console.log(e.toString());
return;
}
// 填写登录表单
await
......@@ -141,28 +156,28 @@ class AutoHome {
.screenshot('m2.png');
// 提交登录表单
await
horseman
.click('[id="btnDealer"]')
.waitForNextPage({ timeout: 5000 })
.catch(Horseman.TimeoutError, function() {
console.log('等待超时');
loginStatus = 'error';
loginMsg = '登录超时';
})
.screenshot('m3.png')
.cookies()
.then(async (cookies) => {
console.log(JSON.stringify(cookies));
const loginSuccess =
await
horseman
.click('[id="btnDealer"]')
.waitForNextPage({ timeout: 5000 })
.screenshot('m3.png')
.exists('#loginout');
if (loginSuccess) {
console.log('登录成功!');
const cookies = await horseman .cookies().close();
console.log(JSON.stringify(cookies));
const cookie_key = this.params.webname + '_cookies';
const client = await redis.createClient();
client.set(cookie_key, JSON.stringify(cookies), redis.print);
client.quit();
const cookie_key = this.params.webname + '_cookies';
const client = await redis.createClient();
await client.set(cookie_key, JSON.stringify(cookies), redis.print);
await client.quit();
console.info('cookie保存成功');
})
.close();
console.info('cookie保存成功');
return 'success';
} else {
await horseman.close();
}
} catch (e) {
throw e;
}
......@@ -171,13 +186,14 @@ class AutoHome {
// 抓取线索
async fetchClues() {
try {
const loginStatus = await this.login();
if (loginStatus) {
try {
await this.login();
console.log('登录成功');
} else {
console.log('登录失败');
} catch (e) {
console.log(e.message);
// 登录失败更新数据库cookie状态
return;
}
return;
const cookies = await this.getCookies();
const cookieJar = new tough.CookieJar();
......@@ -199,6 +215,8 @@ class AutoHome {
// });
// return;
axiosCookieJarSupport(axios);
let rowcount;
let customerIndex = 0;
......@@ -213,7 +231,7 @@ class AutoHome {
params.provinceId = -2;
params.cityId = -2;
params.status = -1;
params.startTime = moment().subtract(7, 'days').format('YYYY.MM.DD');
params.startTime = moment().subtract(3, 'days').format('YYYY.MM.DD');
params.endtime = moment().format('YYYY.MM.DD');
params.pageIndex = 1
params.pageSize = 20;
......@@ -241,7 +259,11 @@ class AutoHome {
for (let clue of clues.result.list) {
customerIndex++;
let $ = cheerio.load(clue.CustomerNameStr);
console.log($.html());
let idMatch = $.html().match(/showCusDetailWithId\("(\d*)"\)/);
clue.CustomerId = idMatch[1] || 0;
console.log('客户序号:', customerIndex);
console.log('客户ID:', clue.CustomerId);
console.log('客户姓名:', $.text());
continue;
console.log('客户号码:', clue.CustomerPhoneStr);
......

269 KB | W: | H:

269 KB | W: | H:

m3.png
m3.png
m3.png
m3.png
  • 2-up
  • Swipe
  • Onion skin
const Promise = require('bluebird');
const redis = require("redis");
const client = redis.createClient();
const Horseman = require('node-horseman');
Promise.promisifyAll(require("redis"));
let info = 'showCusDetailWithId("302761")';
var m = info.match(/showCusDetailWithId\("(\d*)"\)/);
console.log(m);
return;
// class AppError extends Error {
// constructor (message, status) {
//
// // Calling parent constructor of base Error class.
// super(message);
//
// // Capturing stack trace, excluding constructor call from it.
// Error.captureStackTrace(this, this.constructor);
//
// // Saving class name in the property of our custom error as a shortcut.
// this.name = this.constructor.name;
//
// // You can use any additional properties you want.
// // I'm going to use preferred HTTP status for this error types.
// // `500` is the default value if not specified.
// this.status = status || 500;
//
// }
// };
// class AppError extends Error {
// constructor(message) {
// super(message);
// this.message = message;
// // this.name = 'MyError';
// this.name = this.constructor.name;
// }
// }
//
// class BError extends AppError {
// constructor (fields) {
// // Overriding both message and status code.
// super('Request validation failed', 400);
// // Saving custom property.
// this.fields = fields || {};
// }
// };
// function OperationalError(message) {
// if (!(this instanceof OperationalError))
// return new OperationalError(message);
// notEnumerableProp(this, "name", "OperationalError");
// notEnumerableProp(this, "message", message);
// this.cause = message;
// this["isOperational"] = true;
//
// if (message instanceof Error) {
// notEnumerableProp(this, "message", message.message);
// notEnumerableProp(this, "stack", message.stack);
// } else if (Error.captureStackTrace) {
// Error.captureStackTrace(this, this.constructor);
// }
//
// }
//
// response{status:success, message, name:}
// responseError
// function peg$computePosDetails() {
// throw new BError('语法错误', 'idsssss');
// }
//
// try {
// peg$computePosDetails();
// } catch (e) {
// console.log(e);
// };
// return;
const testHorseman = async () => {
const horseman = new Horseman();
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.open('https://www.zhihu.com/')
.then(() => {
console.log((new Date()).toLocaleString());
})
.waitForSelector('.subtitle', { timeout: 2000 })
.screenshot('zhihu.png')
.error(function (e) {
console.error("这是一个错误: ", e);
})
.catch(function(e) {
console.log(e);
console.log('难道是这里?');
})
// .catch(Horseman.TimeoutError, function(e) {
// console.log('等待超时');
// console.log(e);
// console.log((new Date()).toLocaleString());
// })
.close();
}
testHorseman();
return;
async function test (l) {
await Promise.delay(l*1000).then(async function() {
console.log('过了' + l + '秒');
......

269 KB | W: | H:

269 KB | W: | H:

try.png
try.png
try.png
try.png
  • 2-up
  • Swipe
  • Onion skin
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment