【一步步搭建一个React应用-开篇】(https://segmentfault.com/a/11...git地址自己写表格很难录入电影信息,所以选择爬取的信息豆瓣电影主要是爬取电影的封面,主演,年份,产地,简介等,前端有个输入框,输入电影名然后爬取电影信息输入MongoDB进行分析.https://movie.douban.com/subj...这个请求要搜索的电影一般是列表中的第一项,有时第一项找到的是明星信息,需要的电影有一个url指向这个电影的详情,而我们要的信息在详情界面PS中(比较有意思的是,我一开始爬取的时候,我要的信息在这个界面的response里面,直接从response中提取即可。但是后来发现response少了,豆瓣电影里面搜索到的列表信息是js动态渲染的,所有的信息都保存在response的window_data中,于是修改代码,使用phantom来渲染crawlgeneral抓取页面的逻辑)是通过接口A获取电影列表,从列表中提取我们需要的电影详情的urlB,爬取B接口,获取详情,从详情中提取信息。phantom工具通过plantom渲染爬取抓取到的页面,页面中的js代码也会相应执行。一个在cheerioserver端实现jquery功能的库,可以很方便的在响应中的html中获取我们想要的信息爬取项目接口/api/reptile/:namecodevarexpress=require('express');varrouter=express.Router();constCONFIG=require('../config/config')constcheerio=require('cheerio')constrq=require('request-promise')varphantom=require("phantom")复制代码;functiongetMovieSubjectUrl(name){var_ph,_page,_outObj;返回phantom.create().then(ph=>{_ph=ph;返回_ph.createPage();}).then(page=>{_page=page;return_page.open('https://movie.douban.com/subject_search?search_text='+encodeURIComponent(name));}).then(status=>{return_page.property('content')}).then(content=>{_page.close();_ph.exit();returncontent}).catch(e=>console.log(e));}函数getMovieDetail(href,res,next){rq(href).then(str=>{const$=cheerio.load(str)constdata=fillData($)res.json({code:CONFIG.ERR_OK,data})})}functionfillData($){constmovie={thumb:'',actors:'',type:'',time:'',instruct:''}/***为方便提取数据,更换行标签更换*/letinfo_html=$('#info').html().replace(/
/g,'**')lettxt=cheerio.load(info_html).text()txt=txt.replace(/\s+/g,'').split('**')movie.thumb=$('#mainpicimg').attr('src')movie.instruct=$('#link-report').find('span[property]').text()电影.actors=txt[2].split(':')[1].split('/')movie.type=txt[3].split(':')[1].split('/')movie.time=txt[6].split(':')[1]returnmovie}router.get('/:name',function(req,res,next){getMovieSubjectUrl(req.params.name).then(str=>{const$=cheerio.load(str)letdetail=$('.detail')if(detail.length){letaif(detail.eq(0).has('.rating_nums').length){a=detail.eq(0).find('.titlea')}else{a=detail.eq(1).find('.titlea')}getMovieDetail(a.attr('href'),res,next)}else{next(10001)}});})module.exports=router;前端reptile.jsximportReactfrom'react';import{Button,Switch}from"antd-mobile"importcloneDeepfrom"lodash/cloneDeep“从“../util/Util.js”导入Util从“./movieInfo”导入MovieInfo从“./download-form”导入DownForm导出默认类Reptile扩展React.Component{constructor(props){super(props)this.state={m_name:'',m_info:null,}this.reptile=this.reptile.bind(this)}/***爬取数据*/reptile(){if(!this.state.m_name){return}Util.fetch('/api/reptile/'+this.state.m_name).then(data=>{if(data.code){Util.Toast.info(data.message)return}this.setState({m_info:数据.data,})})}render(){return(
