卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章1829本站已运行4109

爬有道翻译结果免登陆

写了个导入文档自动翻译生成新的文档,其中引用了如下的翻译方法,目前我自己测试是没什么限制

已知支持英汉互译,理论上支持各种外文译中,自测,我没需求,就没测试

就几行代码,写的不优雅,但确实可用
package org.example;
 
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
 
public class Main {
    public static void main(String[] args) {
        // 待翻译的关键词
        String kerWord = "如果你有梦想的话,就必须捍卫它。那些一事无成的人总是想告诉你,你也成不了大器。如果你有理想的话,就要去努力实现。";
 
        String url = "http://m.youdao.com/translate"; // 构建搜索URL
        HttpRequest request = HttpRequest.post(url).form("inputtext", kerWord);
 
        HttpResponse response = request.execute();
        // 翻译结果的起始和结束文本
        String startText = "<ul id=\"translateResult\">\n                                                                        <li>";
        String endText = "</li>\n                                                            </ul>";
 
        String text = response.body();
 
        // 获取翻译结果的起始和结束位置
        int startIndex = text.indexOf(startText) + startText.length();
        int endIndex = text.indexOf(endText);
        // 判断是否找到翻译结果,并输出翻译结果
        if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
            String middleText = text.substring(startIndex, endIndex);
            System.out.println("翻译结果为:" + middleText);
        } else {
            System.out.println("未找到匹配的起始和结束文本");
        }
    }
 
}
Python 版本:
from bs4 import BeautifulSoup as bs
from requests import post

def translate(s):
    r = post("http://m.youdao.com/translate", data={"inputtext": s})
    r.encoding = r.apparent_encoding
    soup = bs(r.text, "html.parser")
    ele = soup.find("ul", {"id": "translateResult"})
    if ele:
        li = ele.find("li")
        if li:
            return li.text
    return ""

print(translate("hello"))
 
卓越飞翔博客
上一篇: python控制打印机批量打印文件
下一篇: 用python制作扫雷

相关推荐

留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏