https://translate.google.cn/m?sl=auto&tl=en&hl=zh-CN&q=笑一笑
將上面的地址輸入瀏覽器,能得到翻譯結果,可用以下方法
測試了10分鐘后,再用時請求超時,一小時后,重新測試時,發現又可以用了
private void button18_Click(object sender, EventArgs e)
{
EN.Text = GoogleTranslate.Translate(CHT.Text);
}
弊端是可能谷歌翻譯網頁打不開,這個就沒辦法用了
public class GoogleTranslate
{
private static string GoogleTranslateUrl = "https://translate.google.cn/";
private static string GoogleTranslateAPI = "https://translate.google.cn/m?sl=auto&tl={0}&hl={1}&q={2}";
/// <summary>
/// 谷歌翻译
/// </summary>
/// <param name="text">待翻译文本</param>
/// <returns>翻译后文本</returns>
public static string Translate(string text)
{
CookieContainer cc = new CookieContainer();
string googleTransUrl = string.Format(GoogleTranslateAPI, "en", "zh-CN", HttpUtility.UrlEncode(text));
var ResultHtml = GetResultHtml(googleTransUrl, cc, GoogleTranslateUrl);
string ResultText = "";
// 匹配 <div class="result-container">laugh</div>
Regex rs = new Regex("<div class=\"result-container\">(.*?)(?<lan>(.*?))</div>");
MatchCollection matches = rs.Matches(ResultHtml);
int i = 0;
//遍历所有的img标签对象
foreach (Match match in matches)
{
//获取所有Img的路径src,并保存到数组中
string MaStr = match.Groups["lan"].Value;
ResultText = MaStr;
}
return ResultText;
}
private static string GetResultHtml(string url, CookieContainer cookie, string referer)
{
var html = "";
var webRequest = WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = "GET";
webRequest.CookieContainer = cookie;
webRequest.Referer = referer;
webRequest.Timeout = 20000;
webRequest.Headers.Add("X-Requested-With:XMLHttpRequest");
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36";
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
html = reader.ReadToEnd();
reader.Close();
webResponse.Close();
}
}
return html;
}
}