从 pubchem 下载 json- 文件
Download json-file from pubchem
我的任务是仅使用查询字符串(例如 h2o)和 JS 从网站 (pubchem) 下载 json 文件。我知道解析是可能的,但是代码太多了,因为我需要解析页面数才能到达目的地。还有其他选择可以解决问题吗?
使用 google 没有给我任何想法):
如果您真的想自动执行此操作,您仍然需要进行一些解析,因为仅使用查询参数即可将您带到列出 'articles' 的主页,您需要进去查找URL 将为您提供 JSON 格式。但!我认为您可以对其进行“逆向工程”,因为文章的 URLS 及其 JSON 格式非常相似。
我查看了该网站并尝试下载他们为 https://pubchem.ncbi.nlm.nih.gov/compound/3076959 and it turns out to get the JSON representation this was the 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
到运行。不要忘记安装依赖项。
我的任务是仅使用查询字符串(例如 h2o)和 JS 从网站 (pubchem) 下载 json 文件。我知道解析是可能的,但是代码太多了,因为我需要解析页面数才能到达目的地。还有其他选择可以解决问题吗? 使用 google 没有给我任何想法):
如果您真的想自动执行此操作,您仍然需要进行一些解析,因为仅使用查询参数即可将您带到列出 'articles' 的主页,您需要进去查找URL 将为您提供 JSON 格式。但!我认为您可以对其进行“逆向工程”,因为文章的 URLS 及其 JSON 格式非常相似。
我查看了该网站并尝试下载他们为 https://pubchem.ncbi.nlm.nih.gov/compound/3076959 and it turns out to get the JSON representation this was the 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
到运行。不要忘记安装依赖项。