代码之家  ›  专栏  ›  技术社区  ›  usuario

elementhandle.$eval pagefunction未执行

  •  0
  • usuario  · 技术社区  · 8 年前

    我正在使用puppeteer版本1.6.0分析HTML表

    // inside the rowMarket variable I store all the rows of a table
    rowMarket = await.page.$$('#searchTextResults > tbody > tr');
    

    现在,我要对所有这些列进行迭代,并为每一行获取一些TD列的文本。

    如果我使用下面的代码,一切正常。

    for(i=0<rowMarket.length;i++){
      nameComponent = await rowMarket[i].$('td:nth-child(1) > a');
      iT = await nameComponent .getProperty('innerText');
      json = await iT.jsonValue();
    
      otherComponent = await rowMarket[i].$(' ... ');
      // ... I repeat the same stuff for every column.
    }
    

    为了重用一些代码而不是大量复制和粘贴,我定义了下一个函数

    async function getContent(element){
      innerText = await element.getProperty('innerText');
      json = await innerText.jsonValue();
      return json;  
    }
    

    所以我可以用这种方式重构previus代码

    for(i=0<rowMarket.length;i++){
      nameComponent = await rowMarket[i].$('td:nth-child(1) > a');
      nameText = getContent(nameComponent);
    
      otherComponent = await rowMarket[i].$(' ... ');
      otherText = getContent(otherComponent);
    
      // ...
    }
    

    但在我发现的文件中 $eval function 这似乎是一个奇妙的组合,我正试图做的手。

    接下来我重构代码。我觉得它很干净,很紧凑。

    for(i=0<rowMarket.length;i++){
      nameText = await rowMarket[i].$eval('td:nth-child(1) > a', getContent);
      otherText = await rowMarket[i].$eval(' ...', getContent);
      // ...
    }
    

    但我会得到下一个错误

    (node:8056) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: elemento.getProperty is not a function
        at dentroElemento (__puppeteer_evaluation_script__:2:30)
        at ExecutionContext.evaluateHandle (c:\webscraping\node_modules\puppeteer\lib\ExecutionContext.js:97:13)
        at <anonymous>
        at process._tickCallback (internal/process/next_tick.js:188:7)
    

    我真的不理解这个错误,因为如果在“独立”模式下调用函数,它会正常工作。

    我也试过这个

    for(i=0<rowMarket.length;i++){
      nameText = await rowMarket[i].$eval('td:nth-child(1) > a', e => console.log('hello?'));
    }
    

    但是hello字符串永远不会登录到控制台。所以我认为问题是pageFunction函数没有被调用。或者我的代码有问题。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Carsten    8 年前

    await rowMarket[i].$('td:nth-child(1) > a'); .getProperty()

    async function getContent(elementHandle){
      innerText = await elementHandle.getProperty('innerText');
      ...
    

    .$eval

    nameText = await rowMarket[i].$eval('td:nth-child(1) > a', getContent);

    async function getContent(element){
      innerText = await element.innerText;