1 个回答

谢邀,楼主既然用node,那就没必要使用phantomjs了,它已经不维护了,使用ChromeHeadless即可。
需要安装两个依赖

yarn add puppeteer cheerio

代码如下

const puppeteer = require('puppeteer');
const cheerio = require('cheerio');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://www.baidu.com/s?wd=segmentfault');
  const content = await page.content();

  const $ = cheerio.load(content, { decodeEntities: false });
  $('.result.c-container').each((index, el) => {
    console.log(
      $(el)
        .find('h3 a')
        .text()
    );
  });

  await browser.close();
})();

运行结果

SegmentFault
关于我们 - SegmentFault
【译】MVC 在前端已死? - leozdgao - SegmentFault
segmentfault - SF的创建团队和背后的故事? - SegmentFault
推荐的文章 - SegmentFault
SegmentFault - 杭州堆栈科技有限公司 - SegmentFault
为什么我们选择 segmentfault 写作? - 前沿开发团队 - SegmentFault
App 下载 - SegmentFault
segmentfault - 文章 - SegmentFault
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题