简体   繁体   English

从DB解析JSON并显示在前端

[英]Parsing JSON from DB and displaying on the front-end

Okay, so basically I have a web scraper, and I save the web scraper information into a local database called "db.json"好的,所以基本上我有一个网络爬虫,我将网络爬虫信息保存到一个名为“db.json”的本地数据库中

I was wondering at how about to tackle into implementing it and having the information display in the view.我想知道如何解决实现它并在视图中显示信息。 I'm used to working in like PSQL, so doing this is different for me.. I appreciate the help and I plan on setting up like cron jobs and stuff like that as well but I'll do that later on.我习惯于像 PSQL 那样工作,所以这样做对我来说是不同的..我很感激你的帮助,我计划设置像 cron 作业之类的东西,但我稍后会这样做。

The current partial-jobs maps through out PSQL database and grabs example information right now so it will be changed..当前的部分作业映射到 PSQL 数据库并立即获取示例信息,以便对其进行更改。

I was also having trouble getting it to the grab the jobs title for more.. organized json but for exmaple我也很难让它获取更多的职位名称.. 有组织的 json 但例如

job: jobs.title

which I figured would get the jobs title didn't get anything is it because I have it outside of the function?我认为会获得职位的职位没有得到任何东西,是因为我在职能之外拥有它吗?

Here is the code :这是代码:

The pushing of the information to the DB is located at the bottom of the searchJobs function.将信息推送到 DB 位于 searchJobs 函数的底部。

webScraper.js : webScraper.js :

debug = require("../models/conn");
const puppeteer = require("puppeteer");
const axios = require("axios");
const cheerio = require("cheerio");
const db = require("../public/scripts/db")

async function searchJobs(i) {
  const url = await axios
    .get("https://indeed.com/jobs?q=Web+Developer&l=Atlanta&fromage=last")
    .then(response => response)

    .then(res => {
      const jobs = [];
      const $ = cheerio.load(res.data);

      $(".result").each((index, element) => {
        const title = $(element)
          .children(".title")
          .text();
        const linkToJob = $(element)
          .children(".title")
          .children("a")
          .attr("href");
        const body = $(element)
          .children(".summary")
          .text();
        jobs[index] = { title, linkToJob, body };
      });
      console.log(jobs);
      // Push jobs to JSON DB
      db.get('jobs').push({
        job: jobs
      }).write();
      return jobs;
    });
  return url;
}

This is the script that writes the information to a json file.这是将信息写入 json 文件的脚本。

db.js :数据库.js:

low = require("lowdb"),
    FileSync = require("lowdb/adapters/FileSync");


const adapter = new FileSync('db.json')
const db = low(adapter)

db.defaults({ jobs: [], body: []})
    .write()


module.exports = db;

module.exports = searchJobs;

This is the jobs route这是工作路线

jobs.js :工作.js:

    const express = require("express"),
  router = express.Router();
jobModel = require("../models/jobModel");

// gets job page
router.get("/", async function(req, res) {
  const jobData = await jobModel.getAllJobs();

  console.log(jobData);

  res.render("template", {
    locals: {
      title: "jobs",
      jobData: jobData
    },
    partials: {
      partial: "partial-jobs"
    }
  });
});

module.exports = router;

You don't need to create any kind of models structure for such a simple task using lowdb .您不需要使用lowdb为这样一个简单的任务创建任何类型的模型结构。

Your searchJobs sets jobs wrong inside db.json , and that's because at the end of the scraping you push the whole jobs array to a field named job that belongs to the jobs .searchJobsjobs错了内部db.json ,那是因为在拼抢结束时,你push了整个jobs阵列的一个字段命名job属于jobs That will obviously end up with data like this:这显然最终会得到这样的数据:

{
  "jobs": [
    {
      "job": [
        {
          "title": "...",
          "linkToJob": "...",
          "body": "..."
        },
        {
          "title": "...",
          "linkToJob": "...",
          "body": "..."
        },
        ...
    }
  ],
  "body": []
}

which is not what you want.这不是你想要的。 So, instead of using:所以,而不是使用:

db.get('jobs').push({
  job: jobs
}).write();

you must use:你必须使用:

db.set('jobs', jobs).write();

and then you'll have the data JSON format like this:然后你将拥有这样的数据 JSON 格式:

{
  "jobs": [
    {
      "title": "...",
      "linkToJob": "...",
      "body": "..."
    },
    {
      "title": "...",
      "linkToJob": "...",
      "body": "..."
    },
    ...
  ],
  "body": []
}

and now you have a proper jobs collection which you can use it to display the data.现在你有了一个合适的jobs集合,你可以用它来显示数据。

Express server has a template engine ( "Using template engines with Express" ) which supports ( among others ) EJS templates. Express 服务器有一个模板引擎( “在 Express 中使用模板引擎” ),它支持(除其他外EJS模板。 You can use an EJS template and get/pass jobs to it inside the root route:您可以使用 EJS 模板并在根路由中获取/传递作业给它:

Code for express server file server.js快速服务器文件server.js代码

const low = require("lowdb");
const FileSync = require("lowdb/adapters/FileSync");
const express = require('express');
const app = express();
const port = 3000;

const adapter = new FileSync('db.json');
const db = low(adapter);

// Set express views template engine to EJS
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  // Get the jobs collection
  const jobs = db.get('jobs').value();

  // Render the jobs EJS template by passing the jobs
  res.render("jobs", { jobs });
});

app.listen(port, () => console.log(`Listening on port ${port}!`))

EJS template for rendering jobs jobs.ejs :用于呈现作业jobs.ejs EJS 模板:

...
<body>
  <section id="jobs">
  <% for(const job of jobs) {%>
    <div class="job">
      <a href="<%= job.linkToJob %>"><h3><%= job.title %></h3></a>
      <p><%= job.body %></p>
    </div>
  <% } %>
  </section>
</body>
...

And the final webScraper.js :最后的webScraper.js

const axios = require("axios");
const cheerio = require("cheerio");
const db = require("./db");

async function searchJobs() {
  const url = await axios
    .get("https://indeed.com/jobs?q=Web+Developer&l=Atlanta&fromage=last")
    .then(response => response)

    .then(res => {
      const jobs = [];
      const $ = cheerio.load(res.data);

      $(".result").each((index, element) => {
        const title = $(element)
          .children(".title")
          .text();
        const linkToJob = $(element)
          .children(".title")
          .children("a")
          .attr("href");
        const body = $(element)
          .children(".summary")
          .text();
        jobs.push({ title, linkToJob, body });
      });

      // Push jobs to JSON DB
      db.set('jobs', jobs).write();

    });
}

Now if you start the express server and visit the root route, you'll see something like this ( after you've run webScraper.js of course ):现在,如果您启动 express 服务器并访问根路由,您将看到如下内容(当然是在您运行webScraper.js之后):

 .job { margin-bottom: 10px; border: 1px grey solid; padding: 10px; border-radius: 5px; background-color: lightgray; }
 <section id="jobs"> <div class="job"> <a href="/rc/clk?jk=45633fe1e5f39cc8&amp;fccid=0e1982cac02545cc&amp;vjs=3"> <h3>Freelance Web Developer</h3> </a> <p>Extensive knowledge of HTML, CSS, Javascript/jQuery.</p> </div> <div class="job"> <a href="/rc/clk?jk=b554d8be38d65cba&amp;fccid=8c101aef95dbfdf6&amp;vjs=3"> <h3>Web Developer</h3> </a> <p>VenU is looking for a talented and reliable developer to join an elite development team. Applicants must be proficient in Responsive Design, with experience…</p> </div> <div class="job"> <a href="/rc/clk?jk=8edc3f88b6ec3083&amp;fccid=9899b2a8ca7c5e21&amp;vjs=3"> <h3>Web Developer</h3> </a> <p>We&#39;re looking for a web developer with an excellent eye for design as well as strong HTML &amp; CSS skills. The web developer will be responsible for creating new… </p> </div> </section>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM