0

我的任务是仅使用查询字符串(例如 h2o)和 JS 从网站(pubchem)下载 json 文件。我知道可以进行解析,但是代码太多了,因为我需要解析很多页面才能获得目的地。有没有其他选择可以解决这个问题?使用谷歌没有给我任何想法):

4

1 回答 1

0

如果您真的想自动执行此操作,您仍然需要进行一些解析,因为仅使用查询参数会将您带到列出“文章”的主页,并且您需要进入查找将为您提供的 URL JSON 格式。但!我认为你可以“逆向工程”它,因为文章的 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 端点,然后您可以从那里将响应保存到您机器上的文件中。

这是一个示例,说明如何使用axiosNodeJSfs模块执行此操作,以便将文件保存到您的计算机。

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.jsexample 的文件中,您可以使用node app.js它来运行它。不要忘记安装依赖项。

于 2020-07-22T17:16:48.727 回答