【发布时间】:2021-09-09 14:27:30
【问题描述】:
我正在使用 Puppeteer 构建一个自动购物机器人。我已经使用addToCart 将产品添加到购物车中。添加产品后,我想在同一个浏览器会话中打开一个新 url,但它不起作用。
const puppeteer = require("puppeteer");
const product_url =
"https://www.amazon.com/gp/product/B08ZL7LZW3?pf_rd_r=J6QNRZDRJ7Z8FSF2HVXR&pf_rd_p=6fc81c8c-2a38-41c6-a68a-f78c79e7253f&pd_rd_r=d3adff00-5e6f-4456-8fd0-bd187f2ff86d&pd_rd_w=oO6kF&pd_rd_wg=aoGGq&ref_=pd_gw_unk";
const checkout_url = "https://www.amazon.com/gp/buy/shipoptionselect/handlers/display.html?hasWorkingJavascript=1";
async function givePage() {
const browser = await puppeteer.launch({
headless: false,
});
const page = await browser.newPage();
return page;
}
async function addToCart(page) {
await page.goto(product_url);
await page.waitForSelector(
"button[class='single_add_to_cart_button button alt']"
);
await page.click(
"button[class='single_add_to_cart_button button alt']",
(elem) => elem.click()
);
}
async function checkout() {
var page = await givePage();
await addToCart(page);
await page.waitForNavigation();
const page2 = await browser.newPage(); // open new tab
await page2.goto("https://www.amazon.com/gp/buy/shipoptionselect/handlers/display.html?hasWorkingJavascript=1"); // go to github.com
await page2.bringToFront(); // make the tab active
}
checkout();
【问题讨论】:
-
你的
browser变量被声明为insidegivePage(),所以你不能在checkout()函数中使用它。
标签: javascript node.js async-await puppeteer