【问题标题】:Is there a way to translate only specific elements on the page using Google Translate?有没有办法使用谷歌翻译只翻译页面上的特定元素?
【发布时间】:2022-01-13 04:18:12
【问题描述】:

我想在我的 HTML 页面上嵌入谷歌翻译;但是,我希望它只翻译一个特定的<div>。这是一个例子:

<body>
    <h1>Welcome to the webpage!</h1>
    <hr/>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>In sollicitudin nulla urna, a feugiat purus volutpat eu.</p>
    <p>Phasellus ut scelerisque nisi, id elementum eros.</p>
    <p>Etiam eu lectus pharetra, rhoncus quam ultricies, semper ligula.</p>
    <p>Curabitur aliquet arcu non elementum pellentesque.</p>
    <p>Nam suscipit sit amet diam a dictum.</p>
    <br>
    <div id="parts" style="padding-top: 8px;">
        <button id="text_1">Hello</button>
        <button id="text_2">How</button>
        <button id="text_3">Are</button>
        <button id="text_4">You</button>
    </div>
</body>

所以,我只想翻译 #parts 中的元素。

有没有办法完成它?

谢谢!

【问题讨论】:

  • 你好@rodion,你能澄清embed google translate部分吗?喜欢在加载页面时翻译此内容并翻译 div 部分下的所有内容?加载网站时没有先前的操作,对吗?
  • @Betjens 我的意思是“翻译此页面”按钮嵌入
  • 是的,但是除了点击加载、悬停、onclick (div) 等按钮之外,还有很多事件。只是想具体一点。
  • @Betjens 我还没有嵌入 GTranslate 代码。我看到OG代码(stackoverflow.com/questions/12243818/…)翻译了整个页面,所以我还没有费心添加它。我应该吗?
  • 这是解决问题的一种方法,但我认为您只是在寻找特定标签(在您的情况下仅是 div)

标签: javascript html google-translate google-translation-api


【解决方案1】:

为了使用 Translate API,您必须实现您的网站可以通过 google 服务器和有效项目进行身份验证的方式,以便它可以使用 API。

执行此操作的最常见方法之一是拥有自己的本地服务器,该服务器将运行谷歌客户端库来验证和处理您的翻译请求。此外,您可以使用该服务器进行调用,以加载包含已翻译内容的页面。

HTML/Javascript 网站 您的本地服务器 谷歌翻译服务

有关它的更多信息,您可以访问:OAUTH2

但是,假设我们不想一路走下去,我们希望实施这个小测试。您仍然需要提供您的 project-idbearer token 才能真正让它在您的页面上运行。

<!DOCTYPE html>
<html>
<body onload="DoTranslation()">
    
<h1>Welcome to the webpage!</h1>
<hr/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>In sollicitudin nulla urna, a feugiat purus volutpat eu.</p>
<p>Phasellus ut scelerisque nisi, id elementum eros.</p>
<p>Etiam eu lectus pharetra, rhoncus quam ultricies, semper ligula.</p>
<p>Curabitur aliquet arcu non elementum pellentesque.</p>
<p>Nam suscipit sit amet diam a dictum.</p>
<br>
<div id="parts" style="padding-top: 8px;">
    <button id="text_1">Hello</button>
    <button id="text_2">How</button>
    <button id="text_3">Are</button>
    <button id="text_4">You</button>
</div>

<script type="text/javascript">
async function DoTranslation() { 
        const parts = document.getElementById('parts').children;
        var payload = [];
        
        for (const elems in parts)
        {
            if (parts[elems].innerText != undefined) { 
                payload.push(parts[elems].innerText);
            }
        }
    
        console.log(payload);
    
        let url = "https://translation.googleapis.com/v3/projects/<my-project-id>:translateText";
        let response = await fetch(url, {
          method: "POST",
          headers: {
            "Authorization": "Bearer <my bearer token>",  // Modified
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ 
            sourceLanguageCode: "en",
            targetLanguageCode: "es",
            contents: payload,
            mimeType: "text/plain",
          }),
        });

        let result = await response.json();
        const translations = result['translations']

        for (let i = 0; i < translations.length; i++) {
            elem_id = "text_" + (i+1); 
            document.getElementById(elem_id).innerText = translations[i]["translatedText"];
        } 
}
</script>

</body>
</html>

输出

您的网站将翻译您的按钮。

那么,我们如何获得项目 ID 和不记名令牌? project-id 必须是您的谷歌项目 ID。转到google cloud platform site 并选择启用了translate api 的那个。

现在要获得bearer token,您可以使用google shell editor 和您的服务帐户文件。有关详细信息,请参阅此link

将您的服务帐户 .json 设置为 google_application_credentials

<my user>@cloudshell:~ (project-id)$ export GOOGLE_APPLICATION_CREDENTIALS="service-account-file.json"

通过运行以下命令获取不记名令牌

<my user>@cloudshell:~ (project-id)$ gcloud auth application-default print-access-token

替换项目 ID 和不记名令牌并运行示例。

要回答这个问题,您可以执行元素翻译,但您需要仔细计划要翻译的元素以避免发送许多翻译请求。您可以构建您的单词堆栈,然后进行调用。此外,它的preferably 为其使用客户端库。

最后,您可以查看这些链接以获取有关此主题的更多信息:

【讨论】:

猜你喜欢
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
  • 2018-05-06
  • 2011-09-12
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多