【发布时间】:2018-08-10 13:56:06
【问题描述】:
我想抓取这个页面:calendar events
用于特定数据,例如 formattedDate 和 description。我如何在 Node.JS 的模块中解决这个问题。我很难理解 Node.JS 中的过程。
任何帮助都会有很大帮助,在此先感谢。
【问题讨论】:
标签: json node.js web-scraping module
我想抓取这个页面:calendar events
用于特定数据,例如 formattedDate 和 description。我如何在 Node.JS 的模块中解决这个问题。我很难理解 Node.JS 中的过程。
任何帮助都会有很大帮助,在此先感谢。
【问题讨论】:
标签: json node.js web-scraping module
很简单,你可以导入请求模块并使用它。例如,请参见下面的代码。
const request = require("request");
request("MY_URL", (error, response, body) => {
console.log('body:', body);
});
首先,您需要解析您的 JSON,这允许您从接收到的 json 中访问字段。
const data = JSON.parse(body);
现在,如果您想访问有关某个事件的一些信息,您需要循环事件并访问您需要的内容,例如:
const events = data.bwEventList.events;
events.map((data, index) => console.log(data.calendar))
最终代码也在Repl.it
【讨论】:
来自 nodeJS 文档here
const http = require('http');
http.get('http://umd.bwcs-hosting.com/feeder/main/eventsFeed.do?f=y&sort=dtstart.utc:asc&fexpr=(categories.href!=%22/public/.bedework/categories/sys/Ongoing%22%20and%20categories.href!=%22/public/.bedework/categories/Campus%20Bulletin%20Board%22)%20and%20(entity_type=%22event%22%7Centity_type=%22todo%22)&skinName=list-json&count=30', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
}
if (error) {
console.error(error.message);
// consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData["bwEventList"]["resultSize"]);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
见console.log(parsedData["bwEventList"]["resultSize"]);
将 parsedData 切片为数组,直到得到你想要的为止
【讨论】: