簡體   English   中英

Chrome控制台執行內容的方式與Visual Studio代碼相同嗎?

[英]Does the Chrome console execute things the same way as Visual Studio Code?

我想在網上搜尋折扣鏈接,所以我做到了。 當我在控制台上測試代碼時, data2 (這是我存儲的鏈接數組)是正確的,符合我的預期。 data2僅列出具有折扣的鏈接。

這段代碼寫在Chrome控制台上

但是,當我在VSCode控制台上運行時,最終得到了不同的結果( data2現在具有所有鏈接,而不僅僅是折扣鏈接)。

這段代碼寫在VisualStudioCode上

你能告訴我區別嗎? 我懷疑我的VScode中的“ if”條件無法適應導致這種情況。

注意:我在Chrome上運行的代碼是從VSCODE復制的,邏輯完全相同。

您的代碼存在一些問題。

首先,您嘗試訪問的頁面會動態加載其內容,因此您可能要等待使用page.waitForSelector()將選擇器字符串指定的元素添加到DOM中:

await page.waitForSelector('#app > div > div.container > div.now-list-restautants > div > div > a > div.info-restaurant > p > i');

此外,在page.evaluate()內部, page.evaluate()變量jq

document.getElementsByTagName('head')[0].appendChild(jq); // jq is not defined

此外,您不必要地等待兩次result 您可以返回result

return result;

最后,請確保在完成爬取鏈接后使用的是browser.close()

await browser.close();

下面列出的其余問題與樣式有關,而與功能無關。

您應盡可能使用letconst而不是var ):

const arr = ... // good
var arr = ...   // bad

如果要將可迭代對象轉換為數組,請使用傳播語法 ,而不是Array.from()source ):

[...elements]        // good
Array.from(elements) // bad

您可以獲取href使用的元素屬性href屬性,因此,你不需要使用getAttribute('href')

element.querySelector('.item-content').href                 // good
element.querySelector('.item-content').getAttribute('href') // bad

這是一個完整的工作示例:

'use strict';

const puppeteer = require('puppeteer');

let scrape = async () => {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();

  await page.goto('https://www.now.vn/ho-chi-minh/food/danh-sach-dia-diem-phuc-vu-ca-phe,nuoc-ep-sinh-to,16,70-giao-tan-noi');

  await page.waitForSelector('#app > div > div.container > div.now-list-restautants > div > div > a > div.info-restaurant > p > i');

  const result = await page.evaluate(() => {
    // document.getElementsByTagName('head')[0].appendChild(jq);
    const data2 = [];
    const elements = document.querySelector('#app > div > div.container > div.now-list-restautants > div').children;
    const arr = [...elements];
    const regex = '';

    arr.shift();

    arr.forEach((element, index) => {
      const tagi = document.querySelector('#app > div > div.container > div.now-list-restautants > div > div:nth-child(' + (index + 2) + ') > a > div.info-restaurant > p > i');

      if (element.contains(tagi)) {
        data2.push(element.querySelector('.item-content').href);
      }
    });

    return data2;
  });

  await browser.close();

  return result;
};

scrape().then(value => {
  console.log(value);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM