我正在尝试获取 iframe 内的美元值(75.12 美元)。我可以这样做存储 iframe:
var frm = document.getElementsByTagName("iframe")[0]
但是我不能继续做类似的事情
frm.contentWindow.document.getElementsByTagName("div")
因为我收到有关跨源框架的安全错误。
有没有办法以纯文本形式存储变量
frm
的内容?或者你有什么建议?
iframe 看起来像这样:
<iframe class="transact-client-iframe transact-client-open" name="transact-client" src="https://examplesite.com">
'#document (https://examplesite.com)
<!DOCTYPE html>
<html lang="en-us">
<head></head>
<body class="transact__layout--flex">
<div class="animated idx" style="display: none;"></div>
<div id="ufst" class="vetyu-apptn">
<div class="apptn">
<div class="apptn_header"></div>
<div class="apptn_content">
<div class="py-values">
<div class="py-values_wallet">
<div class="py-values_balance">
<div id="vetyu6" class="help-popout vetyu-view"></div>
<div class="py-value">$75.12</div>
</div>
</div>
<div class="row align-center"></div>
<div class="py-values_ctas"></div>
<div class="py-values_preferences"></div>
</div>
</div>
</div>
</div>
<form style="display: none"/></form>
</body>
</html>
</iframe>
如果您不控制 iframe 的源,那么最好的选择是使用后端代理。 没有直接的 JS 解决方案可以安全绕过跨域安全策略。
发送 HTTP 请求,使用后端语言从 iframe 源获取 HTML 内容,从内容中提取所需的值,然后将其返回给客户端。
后端:
const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');
const app = express();
app.get('/get-balance', async (req, res) => {
try {
// fetch iframe content
const response = await axios.get('https://examplesite.com');
const html = response.data;
// parse HTML with Cheerio
const $ = cheerio.load(html);
const balance = $('.py-value').text(); // element containing value
// return value to client
res.json({ balance: balance.trim() });
} catch (error) {
console.error('Error fetching iframe content:', error.message);
res.status(500).json({ error: 'Failed to fetch balance' });
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
前端
fetch('http://localhost:3000/get-balance')
.then((response) => response.json())
.then((data) => {
console.log('Balance:', data.balance);
document.getElementById('balance').innerText = data.balance;
})
.catch((error) => console.error('Error:', error));
后端(PHP 脚本):
<?php
header('Content-Type: application/json');
function getBalance() {
$url = 'https://examplesite.com';
// cURL to fetch HTML content
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
if (curl_errno($ch)) {
curl_close($ch);
return ['error' => 'Failed to fetch content'];
}
curl_close($ch);
// parse html
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
// locate our element
$xpath = new DOMXPath($dom);
$balanceNode = $xpath->query("//div[@class='py-value']");
if ($balanceNode->length > 0) {
$balance = trim($balanceNode->item(0)->textContent);
return ['balance' => $balance];
}
return ['error' => 'Balance not found'];
}
// output response
echo json_encode(getBalance());
?>
前端:
fetch('http://domain.tld/get_balance.php')
.then((response) => response.json())
.then((data) => {
if (data.error) {
console.error('Error:', data.error);
} else {
console.log('Balance:', data.balance);
document.getElementById('balance').innerText = data.balance;
}
})
.catch((error) => console.error('Fetch error:', error));