函数getQAfromAmazon(productID)
返回productInfo
中的值。
但对于这一行:
const product = await getQAfromAmazon(productID);
console.log("product is:" , product);
结果是:product is: undefined
如何将结果插入产品?
const express = require('express');
const app = express();
const puppeteer = require('puppeteer');
const fs = require('fs');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); //for public api
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(express.urlencoded({ extended: false }));
app.use(express.json())
app.use(express.static('../client'));
app.post('/getQuestionsAndAnswers', async(req, res) => {
console.log("req.body.productId", req.body.productId);
let productID = req.body.productId;
const product = await getQAfromAmazon(productID);
console.log("product is:", product);
});
app.listen(3000);
async function getQAfromAmazon(productID) {
puppeteer.launch({
headless: true,
slowMo: 250,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--window-size=1920,1080', '--user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3312.0 Safari/537.36"']
})
.then(async browser => {
const page = await browser.newPage();
console.log("go to page");
await page.goto("https://www.amazon.com/ask/questions/asin/" + productID);
console.log("waiting for selector body");
await page.waitForSelector('body');
var productInfo = await page.evaluate(() => {
let questionsArray = [];
let answersArray = [];
console.log("waiting for selector question");
let len = document.querySelectorAll("[id^='question']").length;
console.log("len is: ", len);
let str;
let ans;
for (let i = 1; i < len; i++) {
let question = document.querySelectorAll("div.a-fixed-left-grid-col.a-col-right > a > span")[i - 1].innerText;
console.log("question is: ", question);
str = "#a-page > div.a-section.askQuestionListPage > div:nth-child(7) > div > div > div:nth-child(" + i + ") > div > div.a-fixed-left-grid-col.a-col-right > div.a-fixed-left-grid.a-spacing-base > div > div.a-fixed-left-grid-col.a-col-right > span:nth-child(3)";
if (document.querySelector(str) == null) {
ans = "no answer";
} else {
ans = document.querySelector(str).innerText;
}
questionsArray.push(question);
answersArray.push(ans);
};
var product = {
"questionsArray": questionsArray,
"answersArray": answersArray
};
return product;
});
await browser.close();
console.log("productInfo is:", productInfo);
return productInfo;
}).catch(function(error) {
console.error(error);
});
}
答案 0 :(得分:3)
您的getQAfromAmazon()
没有返回值。 return productInfo;
在puppeteer.launch(...).then(...)
中被调用。
尝试这样的事情:
...
async function getQAfromAmazon(productID) {
return puppeteer.launch({
...
以便getQAfromAmazon
将返回承诺。