美文网首页Electron
Nightmare 爬虫(1)

Nightmare 爬虫(1)

作者: 美味小鱼 | 来源:发表于2018-01-02 17:56 被阅读126次
    nightmare导图

    简介

    Nightmare 可以用来做测试和爬虫,它提供了一些很简单的 API 比如(type click goto)等,并让用户可以像写同步代码那样来编写自己的逻辑,底层使用 Electron,

    API 代码示例

    举个简单的例子,搜狗提供了微信公众号文章的搜索,那我们就来做一个简单的实验。

    Select

    首先用 chrome 或者火狐开发者工具找到搜狗的搜索框和搜索按钮的select

    搜索框有个 id 叫 query,锁定。
    这个按钮有个 class 叫 swz ,查了一下整个页面只有一个,锁定。

    代码

    import Nightmare from 'nightmare';
    const nightmare = Nightmare({ show: true });
    
    nightmare
      .goto('https://weixin.sogou.com')
      .type('#query', '爬虫')
      .click('#swz')
      .wait('.news_list')
      .evaluate(()=>{
           let res = {}
            res.urls = []
           document.querySelectorAll('.txt-box h3 a').forEach((el,index)=>{
             res.urls.push(el.href)
           })
          res.next = document.querySelector('#sogou_next').href
          return res
          })
      .end()
      .then(console.log)
      .catch((error) => {
        console.error('Search failed:', error);
      });
    
    • goto 进入页面
    • type#query 这个输入框这里输入 爬虫两个字
    • click 模拟鼠标操作点击搜索按钮
    • wait 现在很多页面的数据都是通过 js 加载的(直接同那个response 可以搞到的页面用scrapy来爬),就用这个函数等到news_list这个 dom元素出现之后再进行操作。
    • evaluate 这个函数是重点,到这里就进入了浏览器的 js 环境,在这里所有的操作都和在浏览器控制台上的环境一样了,可以在浏览器控制台进行调试。另外需要注意的是这个函数的返回不能是dom元素,比如:return document.querySelector('#sogou_next') 这样在 then 函数中就无法接收了。这里有两个思路,一个是用代码直接将dom元素转换成我们需要的信息,比如一个 js(代码中所示)对象传递出来,另外一个就是直接返回关心的 hmtl 代码(.innerHTML),然后再then函数中转换成js对象。最后,这个函数的参数是可以和node环境相通的,也就是说,这里是nodeeletron的交接的地方,用变量书写逻辑。比如:
    let select = '.txt-box h3 a'
    ......
    .evaluate(()=>{
           let res = {}
            res.urls = []
           document.querySelectorAll(select).forEach((el,index)=>{
             res.urls.push(el.href)
           })
          res.next = document.querySelector('#sogou_next').href
          return res
          },select)
    
    • end() 会结束浏览器进程
    • then 在这里又回到了node环境,可以在这里做数据解析、保存到数据库等操作。

    完整例子

    这是我用 ts 写的一个测试代码

    import * as Nightmare from 'nightmare'
    import { ChromeSetting } from './setting'
    import * as EventEmitter from 'events'
    
    
    
    class Night {
      setting:any
      SOGOURL:string = 'http://weixin.sogou.com'
      ev:any
      constructor(setting:any){
        this.ev = new EventEmitter()
        if(setting){
          this.setting = setting
        }else{
          this.setting = ChromeSetting
          console.log(this.setting)
        }
    
      }
    
      doSearchByKeyWord(key_word:string){
        let night = Nightmare(this.setting)
        return night.goto(this.SOGOURL)
          .type('#query',key_word)
          .click('.swz')
          .wait('.news-list')
          .evaluate(()=>{
           let res = {}
            res.urls = []
           document.querySelectorAll('.txt-box h3 a').forEach((el,index)=>{
             res.urls.push(el.href)
           })
          res.next = document.querySelector('#sogou_next').href
          return res
          })
          .end()
          .then((res)=>{
            console.log(res)
            this.ev.emit('searchResult',res)
          })
    
    
      }
    
      parseUrl(res:any){
        console.log(res.next)
        let night = Nightmare(this.setting)
        return night.goto(res.next)
          .wait('.news-list')
          .evaluate(()=>{
           let res = {}
            res.urls = []
           document.querySelectorAll('.txt-box h3 a').forEach((el,index)=>{
             res.urls.push(el.href)
           })
          res.next = document.querySelector('#sogou_next').href
          return res
          })
          .end()
          .then((res)=>{
            console.log(res)
            this.ev.emit('parseUrl',res)
          })
    
    
      }
    
      goToBaiDu(url:any){
        let night = Nightmare(this.setting)
        return night.goto(url)
          .evaluate(()=>{
            //浏览器环境,执行浏览器部分操作
            return document.title
          })
          .end()
          .then((title)=>{
            //返回的数据进入 node 环境,进行数据处理
    
          })
    
      }
    }
    
    let night =new Night()
    night.doSearchByKeyWord('爬虫')
    
    night.ev.on('searchResult',(res)=>{
      night.parseUrl(res)
    })
    
    night.ev.on('parseUrl',(res)=>{
      console.log(res)
    })
    

    效果

    中途调试太多次,没搜狗禁了,哈哈

    这是再打开了浏览器的情况下,不是测试环境可以关掉浏览器选项

    相关文章

      网友评论

        本文标题:Nightmare 爬虫(1)

        本文链接:https://www.haomeiwen.com/subject/dolqnxtx.html