想法
新年第一篇文章,最近做英语相关的服务做多了,发现有人在做座右铭的东西,我也有了个想法就是想做一个可以随机一个座右铭的工具,每天激励自己,或者看看别人怎么激励自己,顺便学英语。
实施
技术选型就是lumen+python(爬虫)+js bin+mongo
爬虫
首先我找了个网站, ,国外的专门搜集和做UGC座右铭的,感觉还不错,内容丰富,质量很高,还能学英语 ,举例:I believe that if one always looked at the skies, one would end up with wings.
嗯。。。。怎么说呢,还是挺励志的。 那就是他了,
这个网站虽然有api但是不能直接爬,估计给参数做了加密,我懒,所以直接用selenium了,省的分析他的请求逻辑,就是效率不高,不过无所谓了,他这里ugc的内容不多,加上cron一分钟一次。 爬虫主要代码,这个页面是预加载的所以需要自己加个滑动功能window.scrollBy(0, 400);
print('start get')driver.get('https://www.brainyquote.com/')for i in list(range(50)): driver.execute_script("window.scrollBy(0, 400);") time.sleep(2)html = driver.page_sourcesel = Selector(text=html)quotes = sel.xpath("//a[@title='view quote']")for quote in quotes: save_motto(quote, 'all')
cron
1 * * * * /usr/bin/python3 /var/www/cx_motto/spider/moto_spider_list.py
客户端
客户端想了想没必要做页面所以就直接用js bin功能了 主要代码,很简单。
const options = { url: 'http://服务器地址/get_one', headers: { 'User-Agent': 'request' }};function callback(error, response, body) { if (!error && response.statusCode == 200) { const info = JSON.parse(body); console.log(info.data.content) }}
服务端主要代码
服务端使用的lumen想想访问量不会太大哈~
public function getOne(){ $count = DB::collection('mottos')->count(); $skip=random_int(0, $count-1); $oneItem = DB::collection('mottos')->skip($skip)->first(); return response()->json(['data'=>$oneItem]); }
打个包上传到npmjs
我的叫omotto,像我一样懒得可以直接用我的。
npm i omotto -g
运行效果
开放代码~
希望能帮到大家