I have no idea why the for-loop only run once. My intention is making the code run through all elements in foodGroupIdsOnPage1
. But it only runs through the first element now.
Could anyone please explain to me? Thank you for your help in advance.
async function initialize() { const browser = await playwright.chromium.launch({ headless: false }); const context = await browser.newContext(); ////create a new browser context, which means no cookies and cache saved const tab1 = await context.newPage(); return { tab1, context }; } async function GotoPage2() { ////wait for function>>>only run the next command after all the commands inside the next bracket run const page1_foodGroupButton = id.querySelector('a') ////beginning of the for loop await page1_foodGroupButton.click(); }; async function main() { const { tab1, context } = await initialize(); await tab1.goto('https://www.cfs.gov.hk/tc_chi/nutrient/search1.php'); const foodGroupIdsOnPage1 = await tab1.evaluate(async function getFoodGroupsOnPage1() { return [...document.querySelector('.tableResponsive').querySelectorAll('td ')].map(e => e.id); }) for (let id of foodGroupIdsOnPage1) { await tab1.evaluate(id => { const page1_foodGroupButton = document.querySelector('[id=' + `"${id}"` + ']').querySelector('a') ////beginning of the for loop page1_foodGroupButton.click(); }, id); await tab1.waitForTimeout(2000); await tab1.click('[id^=grp] > a'); await tab1.waitForTimeout(2000); const ArrayOfTabs = context.pages(); ////get how many tabs chromium are let tab2 = ArrayOfTabs[1]; ////make active tab to the second tab await tab2.evaluate(async function extractFoodGroupData() { let tableOfAllFoods = []; let rowsOnPage3 = document.querySelector(".colorTable2").querySelectorAll("tr"); for (let row_OnPage3 of rowsOnPage3) { let arrayNutritionOfOneFood = []; let cellsInOneRow = row_OnPage3.querySelectorAll("td"); for (let cell of cellsInOneRow) { arrayNutritionOfOneFood.push(cell.innerText); } tableOfAllFoods.push(arrayNutritionOfOneFood); } }); tab2.close(); tab1.goBack(); return; } } main();
https://stackoverflow.com/questions/66979324/why-does-my-for-loop-code-in-javascript-only-run-once April 07, 2021 at 11:49AM
没有评论:
发表评论