如何用AppleScript或JavaScript获取Chrome中亚马逊英国页面的商品价格
解决方案
AppleScript 实现(结合JavaScript)
可以通过AppleScript调用Google Chrome执行JavaScript代码提取价格,以下是完整实现代码:
tell application "Google Chrome" -- 获取完整价格文本(如£22.86) set rawPrice to execute front window's active tab javascript "document.querySelector('.apexPriceToPay .a-offscreen').textContent.trim();" -- 处理价格,提取整数部分(如22) set cleanPrice to do shell script "echo " & quoted form of rawPrice & " | sed 's/[^0-9]//g' | cut -c1-2" end tell return cleanPrice
代码说明:
- 用
document.querySelector定位价格元素:.apexPriceToPay是外层容器类名,.a-offscreen是承载价格文本的子元素 - 通过Shell命令过滤非数字字符,截取整数部分
纯JavaScript 实现
若直接在浏览器控制台或脚本中使用,可通过以下代码获取价格:
// 获取完整价格字符串 const priceText = document.querySelector('.apexPriceToPay .a-offscreen').textContent.trim(); // 提取数字并转换为整数(可选) const priceValue = parseInt(priceText.replace(/[^0-9.]/g, '')); console.log(priceValue); // 输出22
注意事项
- 亚马逊页面的类名可能随网站更新变动,若代码失效,需重新检查页面元素的选择器
- 若页面加载较慢,需添加等待逻辑:AppleScript中可加入
delay 2等待页面加载完成;JavaScript中可使用MutationObserver监听元素加载状态
内容的提问来源于stack exchange,提问作者Sockie
相关产品推荐
相关产品推荐

