node 使用selenium 爬取页面数据(node爬虫)

2022/2/2 17:42:57

本文主要是介绍node 使用selenium 爬取页面数据(node爬虫),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

什么是selenium-webdriver

selenium-webdriver是一种用于调动浏览器进行操作的插件。本文主要是给node使用,并拥有爬虫获取数据。

操作流程

打开npm网站,搜索selenium-webdriver
https://www.npmjs.com/package/selenium-webdriver

选择自己使用的浏览器,并安装对应的浏览器版本,一定要和自己浏览器的版本一致的驱动程序


写清楚使用的浏览器,并且调用的辅助驱动最好和调用程序放在一个目录下

也chrome版本比较多,如果找不到对应的版本还可以使用firefox,效果基本一致,只是浏览器不一样
本案例使用的就是火狐,读取一个小说网站,并通过css和标签获取章节名和链接地址
先安装模块
npm i selenium-webdriver

下面是全部代码

const {Builder, By, Key, until} = require('selenium-webdriver');
(async function example() {
  let driver = await new Builder().forBrowser('firefox').build();
  try {
    await driver.get('https://m.banzhuchilaohu.com/indexlist/2916/');
// await driver.findElement(By.id('cboxClose')).click()
    
    // await driver.findElement(By.id('kw')).sendKeys('前端', Key.RETURN);
     let items = await driver.findElements(By.css('.chapter li'));
     var list = []
    for(let i=0; i<items.length; i++) {
      let item = items[i];
      // console.log(await  item.getText())
      let title = await item.findElement(By.css("a")).getText();
      let url = await item.findElement(By.css("a")).getAttribute("href");
      list.push({title,url});
      
    }
    console.log(list);


  } finally {
    // await driver.quit();
  }
})();


这篇关于node 使用selenium 爬取页面数据(node爬虫)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程