我正在尝试加载 HTML,直到我的 JS 代码使用 PHP 对其进行翻译。然后我想检索这个翻译后的 HTML 的内容。我做了很多研究,但我似乎做不到。
这是我的 HTML 代码:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Translate Page</title>
</head>
<body>
<div id="content">
<p>This example displays a simple translate button, with no text.</p>
<p>This example displays a simple translate button, with no text.</p>
<div class="notranslate">
<p>This is a paragraph.</p>
<p>
A particle is kept at rest at the top of a sphere of diameter \(42 m\). When disturbed slightly,
it slides down. At what height \( h \) from the bottom, the particle will leave the sphere <br>
(a) \( 14m \)<br>
(b) \( 16m \)<br>
(c) \( 35m \)<br>
(d) \( 70m \)
</p>
</div>
</div>
<script>
function translateContent() {
const allTextNodes = getAllTextNodes(document.body);
const textContent = allTextNodes.map(node => node.textContent.trim()).join(' ');
// Translate content to French using Google Translate
fetch('https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=fr&dt=t&q=' + encodeURIComponent(textContent))
.then(response => response.json())
.then(data => {
const translatedText = data[0].map(sentence => sentence[0]);
replaceTextNodes(allTextNodes, translatedText.join(' '));
})
.catch(error => console.error('Error translating content:', error));
}
function getAllTextNodes(element) {
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, false);
const textNodes = [];
while (walker.nextNode()) {
textNodes.push(walker.currentNode);
}
return textNodes;
}
function replaceTextNodes(nodes, newText) {
let currentIndex = 0;
nodes.forEach(node => {
if (node.nodeType === Node.TEXT_NODE) {
const originalText = node.textContent.trim();
const newTextSlice = newText.slice(currentIndex, currentIndex + originalText.length);
node.textContent = newTextSlice;
currentIndex += originalText.length;
}
});
}
// Trigger translation on page load
window.onload = translateContent;
</script>
</body>
</html>
我试过这个:
<?php
require 'vendor/autoload.php';
use JonnyW\PhantomJs\Client;
// Create a PhantomJS client instance
$client = Client::getInstance();
// Set the path to the PhantomJS binary
$client->getEngine()->setPath('/usr/local/bin/phantomjs');
// Open a webpage
$request = $client->getMessageFactory()->createRequest('translateHTMLUsingJs2.html', 'GET');
// Set the timeout for script execution (in milliseconds)
$request->setTimeout(2000);
// Render the webpage
$response = $client->getMessageFactory()->createResponse();
// Send the request and receive the response
$client->send($request, $response);
// Output the rendered HTML content
echo $response->getContent();
但是它并没有像我希望的那样工作。 你能帮我用 PHP 来做吗? 任何人都会有很大的帮助。请随时发表评论或给我解决方案......
我知道您的 PHP 代码使用了 PhantomJS 的包装器,而 PhantomJS 又是一个无头浏览器。
我猜你的目标是让 PhantomJS 在网页上执行 Google Translate,这样你就可以从 PHP 中提取翻译后的文本。
您正确地认为无头浏览器需要一些时间让谷歌翻译代码完成其工作,但您为此使用了错误的参数。 “超时”与 HTTP 连接有关,您需要延迟,或者更好的是,延迟保存 DOM。 php-phantomjs 参考有一个特定示例来执行此操作:
use JonnyW\PhantomJs\Client;
$client = Client::getInstance();
$client->isLazy(); // Tells the client to wait for all resources before rendering
$request = $client->getMessageFactory()->createRequest();
$request->setTimeout(5000); // Will render page if this timeout is reached and resources haven't finished
注意“isLazy”调用。
旁注