利用a标签下载

由于需要,找到了个名著网站。想下载小说可是没有下载按钮。于是借助开发人员工具写几条代码玩玩。

简单获取一下小说文本,文件名

1
2
text = document.getElementsByClassName("cbdlconlol")[0].innerText;
filename = prompt("这是第几章?")+"."+document.getElementsByClassName("bdnlttluro")[0].innerText+".txt";

创建Blob对象,和url

1
2
3
4
b = new Blob([text], {
type: "text/plain;charset=utf-8"
});
url=URL.createObjectURL(b);

创建a标签并设置好参数,下载。

1
2
3
4
5
6
var element = document.createElement('a');
element.setAttribute('href', url);
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();

全部代码

1
2
3
4
5
6
7
8
9
10
text = document.getElementsByClassName("cbdlconlol")[0].innerText;
filename = prompt("这是第几章?")+"."+document.getElementsByClassName("bdnlttluro")[0].innerText+".txt";
b = new Blob([text], {type: "text/plain;charset=utf-8"});
url=URL.createObjectURL(b);
var element = document.createElement('a');
element.setAttribute('href', url);
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();

网上似乎有个更简单(比上面少两行,不用创建Blob对象)的方法

1
2
3
4
5
6
7
8
text = document.getElementsByClassName("cbdlconlol")[0].innerText;
filename = prompt("这是第几章?")+"."+document.getElementsByClassName("bdnlttluro")[0].innerText+".txt";
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();

封装成函数

1
2
3
4
5
6
7
8
var dlDoc = (text,filename) =>{
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
};

然后就可以下载txt/py/php等文本文件,比如

1
2
3
dlDoc("print('Hello World!')","Hello World.py");
dlDoc("echo('Nice to meet you!');","hi.php");
dlDoc("echo('Glad to meet you!')","hi.sh");


满分是10分的话,这篇文章你给几分,您的支持将鼓励我继续创作!