我想在使用 Tampermonkey 和正则表达式访问特定网站时自动下载 mp3,问题是当我使用正则表达式时,它无法下载 mp3,但当我在“var arg”中使用正常 URL 时,它会自动下载 mp3。我想在访问网站时自动下载mp3,并以与网站上的文件名相同的原始文件名保存mp3。
以下是示例网址:http://188.138.xx.xxx/mp3/12/45/song_mp3_6612.mp3
。
这是我的示例 javascript
// ==UserScript==
// @name New Userscript
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @include http://*/mp3*
// @grant GM_download
// ==/UserScript==
var regex = /^(http:\/\/)(.*)(\/mp3\/.*\/)(.*)$/i;
var arg = { url: regex,
name: "get the filename from orignal filename in regex.mp3"
};
GM_download(arg);
当我直接使用而不使用正则表达式时,它可以工作
// ==UserScript==
// @name New Userscript
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @include http://*/mp3*
// @grant GM_download
// ==/UserScript==
var arg = { url: "http://188.138.xx.xxx/mp3/12/45/song_mp3_6612.mp3",
name: "song.mp3"
};
GM_download(arg);
这是另一个示例链接 这是另一个链接示例:http://62.75.xxx.xx/mp3/5/7e/dj_snake_taki_taki_ft._selena_gomez_ozuna_cardi_b_mp3_17376.mp3 http://188.138.xxx.xxx/mp3/7/d1/rayvanny_ft_diamond_platnumz_mwanza_official_music_video_mp3_19403.mp3 http://188.138.xxx.xxx/mp3/b/52/bad_bunny_feat._drake_mia_video_oficial_mp3_21130.mp3
我尝试了这些正则表达式,但在 tampermonkey 中找不到相同的内容
// ==UserScript==
// @name New Userscript
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @include http://*/mp3*
// @grant GM_download
// ==/UserScript==
var regex = /(\bhttps?:\/\/(?:\d+\.?){4}\/mp3(?:\/[a-z0-9]+)\/[a-z0-9]+\/[.\w+-]+?\.mp3\b)/;
var arg = { url: regex,
name: "filename.mp3"
};
GM_download(arg);
这是 html 元素
<html>
<head>
<meta name="viewport" content="width=device-width">
</head>
<body style="margin: 0px;">
<video controls="" autoplay="" name="media">
<source src="http://188.138.xxx.xxx/mp3/b/52/bad_bunny_feat._drake_mia_video_oficial_mp3_21130.mp3" type="audio/mpeg">
</video>
</body>
</html>
最佳答案
首先,我会走非贪婪的路线。你想消耗尽可能少的量。您还应该专门查找要捕获的字符串末尾的文件扩展名 .mp3
。
然后我的下一个观察结果是众多的捕获组 - 您只需要一个捕获组即可获取整个 URL。
(https?:\/\/.*?\/mp3\/.*?\/.*?\.mp3)
查看regex101
我的最终观察结果是,您使用的是字符串 anchor ^
和 $
。在您的输入字符串中,如果您要查找的网址已经紧接在字符串 ^
开头之后和紧接字符串 $
结尾之前,那么您就不会首先需要正则表达式。
如果您的网址始终与您提供的格式相同,那么您甚至可以更进一步:
(\bhttps?:\/\/(?:\d+\.?){4}\/mp3(?:\/\d+){2}\/[\w+-]+?\.mp3\b)
这将确保所有子文件夹都位于文件夹 \mp3\
下,您可以看到 here .
关于javascript - 使用正则表达式在 tampermonkey 中自动下载 mp3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53357778/