我的任务是仅使用查询字符串(例如h2o)和JS从网站(pubchem)下载json-file。我知道解析是可能的,但这是太多的代码,因为我需要解析的页面数量,以获得目的地。有没有其他办法来解决这个问题?使用谷歌没有给我任何想法):
发布于 2020-07-23 01:16:49
如果你真的想实现自动化,你仍然需要做一些解析,因为只需要使用一个查询参数就可以进入列出“文章”的主页,并且你需要找到提供JSON格式的URL。但!我认为您可以对其进行“反向工程”,因为文章的URLS和它的JSON格式非常相似。
我查看了这个网站,并尝试下载其中一个用于https://pubchem.ncbi.nlm.nih.gov/compound/3076959的文件,结果得到了JSON表示,这是URL https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/748328/JSON/
正如您所看到的,它们非常相似,并且您可能能够弄清楚不同的主题(例如compound )是如何构造JSON输出端点的。
要使用NodeJS下载JSON文件,就是使用node-fetch模块或axios库将http请求发送到JSON端点,然后您可以将响应保存到您的机器上的文件中。
下面是一个示例,说明如何使用axios和NodeJS fs模块将文件保存到您的计算机。
const fs = require("fs");
const fetch = require("node-fetch");
async function downloadASJson(url, fileName) {
const response = await fetch(url);
const jsonContent = await response.buffer();
fs.writeFile(`${fileName}.json`, jsonContent, "utf8", function (err) {
if (err) {
console.log("An error occured while writing JSON Object to File.");
return console.log(err);
}
console.log("JSON file has been saved.");
});
}
try {
downloadASJson(
"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/748328/JSON/",
"2-Methyl-3-(5'-bromobenzofuroyl-2')-4-dimethylaminomethyl-5-hydroxybenzofuran HCl H20"
);
} catch (err) {
console.log(error);
}例如,您将以下代码保存在一个名为app.js的文件中,并且可以使用node app.js来运行它。不要忘记安装依赖项。
https://stackoverflow.com/questions/63039654
复制相似问题