首页 > 解决方案 > 尝试使用 Nodejs 从 HTML 响应中提取信息

问题描述

我正在尝试使用cheerio 和puppeteer 模块从我的HTML 响应中提取电子邮件(myemail@hotmail.com)。但我得到了不同的东西,我根本不需要使用它们。它位于 td/tr 的 p2 类中。同时将 tr 作为参数

这就是我的代码的样子:

const puppeteer = require('puppeteer');
const $ = require('cheerio');
const url = 'https://mywebsite.com';

puppeteer
  .launch()
  .then(function(browser) {
    return browser.newPage();
  })
  .then(function(page) {
    return page.goto(url).then(function() {
      return page.content();
    });
  })
  .then(function(html) {
    $('tr', html).each(function() {
        // putting all the result into the list

      console.log($(this).text());
    });
  })
  .catch(function(err) {
    //handle error
  });

我得到这个输出:

移动邮箱电路

myemail@hotmail.com
邮箱 myemail@hotmail.com 经理秘书

我只需要 myemail@hotmail.com

这是我的 HTML 表:

</td>
                </tr>
                <tr>
                    <td class="p1">E-mail</td>
                    <td class="p2">
                            <span style="float: none; word-wrap: break-word;"> <a href="mailto:myEmal@hotmail.com"> myEmal@hotmail.com
                                    <div style="padding-right: 2px; background-position: -115px -434px; height: 14px !important; float: right" class="ico"></div>
                            </a>
                            </span>
                        </td>

标签: javascripthtmlnode.jspuppeteercheerio

解决方案


尝试在该类的 td 中获取内容。

console.log($(this).find('td.p2').text());

推荐阅读