浏览器 控制台 JavaScript 保存数据到硬盘文件

锦天 2020-11-12 23:19:56
javascript 浏览器 控制台 浏览 控制


写数据到文件 - 方法封装

/**
* 保存数据到指定的文件
* 利用 Blob 对象把要下载的数据转换为二进制
* 然后利用<a>的href属性和download属性,click事件,实现数据下载。
* @param {string} filename 要保存的文件名
* @param {string} str 要保存的文本内容
*/
function saveStringToFile(filename, str) {

// 创建一个 <a> 标签对象
var linkTag = window.document.createElement("a");
// 设置该实例的 download 和 href 属性(HTML 5 标准属性)
linkTag.download = filename;
linkTag.href = window.URL.createObjectURL(new Blob([str]));
// 把刚才手动创建的 <a> 添加到 DOM 文档中
window.document.body.appendChild(linkTag);
linkTag.click(); // 调用点击事件
// 移除刚才添加的子标签
window.document.body.removeChild(linkTag);
}
// 调用测试(字符串可以是任意来源,比如 fetch API 获取的JSON数据)
saveStringToFile("1.txt", "沧海一声笑");

原理解析

  1. HTML 5 a标签 新属性 download

<a>标签的属性downloadhref,用法见 https://www.runoob.com/tags/tag-a.html

在这里插入图片描述
2. HTML 演示

新建test.html,内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a id="app">点击试试</a>
<script>
var linkTag = document.getElementById("app");
var str = "沧海一声笑"; // 要保存的数据
linkTag.href = window.URL.createObjectURL(new Blob([str]));
linkTag.download = "2.txt";
// linkTag.click(); // 代码调用点击事件,也可以鼠标点击后触发。
</script>
</body>
</html>

点击链接后,弹出文件下载框
在这里插入图片描述
3. 应用

使用浏览器看到一些想要保存的数据,可以使用:
- fetch API 获取响应的JSON数据;
- 以上封装的方法保存数据到本地文件

Demo

雪球网-行情 https://xueqiu.com/hq
流程略,代码如下:

function saveStringToFile(filename, str) {

var linkTag = window.document.createElement("a");
linkTag.download = filename;
linkTag.href = window.URL.createObjectURL(new Blob([str]));
window.document.body.appendChild(linkTag);
linkTag.click();
window.document.body.removeChild(linkTag);
}
await fetch("https://xueqiu.com/service/v5/stock/screener/screen?category=CN&size=10&order=desc&order_by=follow7d&only_count=0&page=1&_=1598890471819", {

"credentials": "include",
"headers": {

"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0",
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.5",
"cache-control": "no-cache",
"X-Requested-With": "XMLHttpRequest"
},
"referrer": "https://xueqiu.com/hq",
"method": "GET",
"mode": "cors"
})
.then(function(response) {

return response.json();
})
.then(function(data) {

// console.log("data", data); // josn类型
var str = JSON.stringify(data, null, " ");
var filename = "行情.json";
saveStringToFile(filename, str); // 把提取到的数据保存到文件
});

就可以获取到部分JSON数据。

在这里插入图片描述

  • 文件
    行情.json
{

"data": {

"count": 4069,
"list": [
{

"pct": 1.68,
"symbol": "SH600519",
"current": 1786.5,
"follow7d": 18250,
"name": "贵州茅台",
"type": 11,
"tick_size": 0.01,
"has_follow": false
},
{

"pct": -0.98,
"symbol": "SZ000651",
"current": 54.5,
"follow7d": 15903,
"name": "格力电器",
"type": 11,
"tick_size": 0.01,
"has_follow": false
},
{

"pct": 3.33,
"symbol": "SH600887",
"current": 41.94,
"follow7d": 14033,
"name": "伊利股份",
"type": 11,
"tick_size": 0.01,
"has_follow": false
},
{

"pct": 1.27,
"symbol": "SH603288",
"current": 183.2,
"follow7d": 13156,
"name": "海天味业",
"type": 11,
"tick_size": 0.01,
"has_follow": false
},
{

"pct": -2.83,
"symbol": "SZ002352",
"current": 85.1,
"follow7d": 12627,
"name": "顺丰控股",
"type": 11,
"tick_size": 0.01,
"has_follow": false
},
{

"pct": -1.63,
"symbol": "SH601318",
"current": 76.62,
"follow7d": 9714,
"name": "中国平安",
"type": 11,
"tick_size": 0.01,
"has_follow": false
},
{

"pct": -1.98,
"symbol": "SH600036",
"current": 37.69,
"follow7d": 9505,
"name": "招商银行",
"type": 11,
"tick_size": 0.01,
"has_follow": false
},
{

"pct": -0.21,
"symbol": "SZ000858",
"current": 240,
"follow7d": 8548,
"name": "五粮液",
"type": 11,
"tick_size": 0.01,
"has_follow": false
},
{

"pct": -1.31,
"symbol": "SZ000568",
"current": 149.5,
"follow7d": 8166,
"name": "泸州老窖",
"type": 11,
"tick_size": 0.01,
"has_follow": false
},
{

"pct": -2.56,
"symbol": "SZ000895",
"current": 63.5,
"follow7d": 8080,
"name": "双汇发展",
"type": 11,
"tick_size": 0.01,
"has_follow": false
}
]
},
"error_code": 0,
"error_description": ""
}

以上测试过程,仅供学习参考。

MDN Links

前端基础(HTML,CSS,JavaScript)这块有什么疑问,可以直接百度MDN xxx,基本都会有结果。

以下:

版权声明
本文为[锦天]所创,转载请带上原文链接,感谢
https://wuyujin.blog.csdn.net/article/details/108331790

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple