C#根据单词爬取有道上面的翻译

本文介绍了一种使用C#语言实现的有道翻译API调用方法,通过编写特定的类和方法,能够从有道翻译网站获取英文单词的中文翻译。代码详细展示了如何构造HTTP请求头,设置请求参数,并解析JSON响应以获取翻译结果。
摘要由CSDN通过智能技术生成

这是调用翻译类获取单词翻译的代码:

Translator Translator;
Translator = new Translator();
string chinesesmeaning=Translator.GetTranslate("Apple");//你要查询的英文单词,返回值是翻译结果

 

以下是通过C#爬虫获取有道上英文单词的翻译的类的代码:

class Translator
    {
        public string GetTranslate(string word)
        {
            string trans = "";
            try
            {
                
                var url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule";
                var headers = new WebHeaderCollection();
                headers["Content-Type"] = "application/x-www-form-urlencoded";
                headers["user-agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";
                headers["Referer"] = "https://www.lagou.com/jobs/list_unity3d?labelWords=&fromSearch=true&suginput=";
                var dict = new Dictionary<string, string>()
{
    {"i",word },
    {"from","AUTO" },
    {"to","AUTO" },
    {"smartresult","dict" },
    {"client", "fanyideskweb" },
    {"salt","15808837717114" },
    {"sign","22a6ee9a07d4821f04e50bd029f73de0" },
    {"ts" ,"1580883771711" },
    {"bv","38c3ccbde2d50a86f0f9606d2be5a3d8"},
    {"doctype","json" },
    {"version","2.1"},
    {"keyfrom","fanyi.web"},
    {"action","FY_BY_REALTlME" }
};
                var str = PostInf(url, headers, GetPostArgs(dict));

                using (var dt = JsonDocument.Parse(str))
                {
                    trans = dt.RootElement.GetProperty("translateResult")[0][0].GetProperty("tgt").ToString();
                }
            }
            catch(Exception ex)
            {
                Unitily.Log(ex);
            }
            
            return trans;
        }
        /// <summary>
        /// 把字典转化为请求字符串
        /// </summary>
        /// <param name="dict">参数字典</param>
        /// <returns>返回请求字符串</returns>
        public static string GetPostArgs(Dictionary<string, string> dict)
        {
            StringBuilder sb = new StringBuilder();
            bool first = true;
            foreach (var item in dict)
            {
                if (first)
                {
                    sb.Append(item.Key);
                    sb.Append("=");
                    sb.Append(item.Value);
                    first = false;
                }
                else
                {
                    sb.Append("&");
                    sb.Append(item.Key);
                    sb.Append("=");
                    sb.Append(item.Value);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 发送Post请求
        /// </summary>
        /// <param name="url">连接</param>
        /// <param name="headers">HTTP头</param>
        /// <param name="str">请求字符串</param>
        /// <returns>返回结果</returns>
        public static string PostInf(string url, WebHeaderCollection headers, string str)
        {
            //创建HTTP请求
            var re = WebRequest.Create(url) as HttpWebRequest;
            //设置请求头
            //re.Headers = headers;
            re.ContentType = "application/x-www-form-urlencoded";
            re.UserAgent= "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";
            re.Referer = "https://www.lagou.com/jobs/list_unity3d?labelWords=&fromSearch=true&suginput=";
            //设置访问类型为POST
            re.Method = "POST";
            //写入请求信息
            using (StreamWriter sw = new StreamWriter(re.GetRequestStream()))
            {
                sw.WriteLine(str);
            }
            //获取相应内容
            var ans = re.GetResponse();
            using (var st = new StreamReader(ans.GetResponseStream()))
            {
                return st.ReadToEnd();
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汪汪星河

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值