在网上找下牛的爬虫一直没找到,决心自己写一个,打开小牛翻译开放平台,发现小牛有开放的API接口,这样接非常方便啦。
先打开小牛的网页查看它的api接口解析:
再去控制台找到apikey(登入才有)和post请求需要的data:
接着就可以开始写代码了:
# -*- coding: utf-8 -*-import requests
import json
import sys
import timedef translate(input,output,fromlan,tolan):with open(input,'r',encoding='utf-8') as rfile:lines = rfile.readlines()for line in lines:line = line.strip()translate_url = 'http://api.niutrans.vip/NiuTransServer/translation'headers = {'User-Agent': "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1"}data = {'src_text':line,'from':fromlan,'to':tolan,//登入后找到自己的aipkey加进去就行了'apikey':' '}response = requests.post(url=translate_url, data=data, headers=headers, timeout=5.1)content = response.json()result = content['tgt_text']if (content):print(result)with open(output,'a',encoding='utf-8') as wfile:wfile.write(result) else:print('请求失败!')time.sleep(3)if __name__== "__main__":translate(sys.argv[0], sys.argv[1], sys.argv[2], sys.argv[3])
代码应该没什么大问题,这样就可以了。