Greasy Fork

arXiv下载PDF文件自动重命名为论文名

能够直接把下载的文件名默认修改为论文名,并且符合Windows文件命名规范。会在搜索页面以及单个论文界面产生一个下载论文的超链接,点击即可。[2023-12-17修改版]

目前为 2025-03-25 提交的版本。查看 最新版本

// ==UserScript==
// @name         arXiv下载PDF文件自动重命名为论文名
// @name:en      arXiv downloaded PDF files, automatically renames them to paper titles
// @name:zh-TW   arXiv下載PDF檔案自動重新命名為論文名
// @name:ja      arXivのPDFファイルを論文タイトルに自動リネーム
// @name:ko      arXiv PDF 파일을 논문 제목으로 자동 이름 변경
// @name:fr      Renommage automatique des fichiers PDF d'arXiv avec les titres des articles
// @name:de      arXiv PDF-Dateien automatisch nach Papiertiteln umbenennen
// @name:es      Renombrar automáticamente archivos PDF de arXiv con títulos de artículos
// @name:ru      Автоматическое переименование PDF-файлов arXiv в название статьи
// @name:ar      إعادة تسمية ملفات PDF من arXiv تلقائيًا بعناوين الأوراق البحثية
// @name:pt      Renomear automaticamente arquivos PDF do arXiv com títulos de artigos
// @name:it      Rinominare automaticamente i file PDF di arXiv con i titoli degli articoli
// @description  能够直接把下载的文件名默认修改为论文名,并且符合Windows文件命名规范。会在搜索页面以及单个论文界面产生一个下载论文的超链接,点击即可。[2023-12-17修改版]
// @description:en It can directly modify the downloaded file name to the thesis name by default and conform to the Windows file naming standard. Will generate a hyperlink to download the paper on the search page as well as the individual paper screen, click on it. [modified version 2023-12-17]
// @description:zh-TW 可以直接將下載的檔案名稱預設修改為論文名稱,並符合Windows檔案命名規範。將在搜尋頁面以及單一論文介面產生一個下載論文的超連結,點擊即可。[2023-12-17修改版]
// @description:ja ダウンロードしたファイル名をデフォルトで論文名に直接変更し、Windowsのファイル命名規則に準拠。検索ページと個々の論文画面に論文をダウンロードするハイパーリンクを生成し、クリックするだけ。[2023-12-17修正版]
// @description:ko 다운로드한 파일 이름을 기본적으로 논문 이름으로 직접 수정하고 Windows 파일 이름 지정 규칙을 준수합니다. 검색 페이지와 개별 논문 화면에 논문을 다운로드할 하이퍼링크를 생성하여 클릭만 하면 됩니다. [2023-12-17 수정 버전]
// @description:fr Il peut modifier directement le nom du fichier téléchargé par défaut en nom de thèse et se conformer aux normes de dénomination de fichiers Windows. Générera un lien hypertexte pour télécharger l'article sur la page de recherche ainsi que sur l'écran de l'article individuel, il suffit de cliquer. [version modifiée 2023-12-17]
// @description:de Kann den heruntergeladenen Dateinamen standardmäßig direkt in den Papiernamen ändern und entspricht den Windows-Dateibenennungsstandards. Generiert einen Hyperlink zum Herunterladen des Papiers auf der Suchseite sowie auf dem Bildschirm des einzelnen Papiers, einfach klicken. [modifizierte Version 2023-12-17]
// @description:es Puede modificar directamente el nombre del archivo descargado de manera predeterminada al nombre de la tesis y cumplir con los estándares de nomenclatura de archivos de Windows. Generará un hipervínculo para descargar el artículo en la página de búsqueda, así como en la pantalla del artículo individual, solo haga clic. [versión modificada 2023-12-17]
// @description:ru Может напрямую изменять имя загруженного файла по умолчанию на название статьи и соответствовать стандартам именования файлов Windows. Создаст гиперссылку для загрузки статьи на странице поиска, а также на экране отдельной статьи, просто щелкните. [измененная версия 2023-12-17]
// @description:ar يمكنه تعديل اسم الملف المُنزّل بشكل افتراضي مباشرةً إلى اسم الرسالة والتوافق مع معايير تسمية الملفات في Windows. سيولّد رابطًا تشعبيًا لتنزيل الورقة البحثية في صفحة البحث وكذلك على شاشة الورقة الفردية، فقط انقر. [النسخة المعدلة 2023-12-17]
// @description:pt Pode modificar diretamente o nome do arquivo baixado por padrão para o nome da tese e estar em conformidade com os padrões de nomenclatura de arquivos do Windows. Gerará um hiperlink para baixar o artigo na página de pesquisa, bem como na tela do artigo individual, basta clicar. [versão modificada 2023-12-17]
// @description:it Può modificare direttamente il nome del file scaricato per impostazione predefinita con il nome della tesi e conformarsi agli standard di denominazione dei file di Windows. Genererà un collegamento ipertestuale per scaricare l'articolo nella pagina di ricerca e nella schermata del singolo articolo, basta fare clic. [versione modificata 2023-12-17]
// @namespace    Tampermonkey
// @version      0.1.2
// @author       Aspen138
// @match        *://arxiv.org/abs/*
// @match        *://arxiv.org/search/*
// @icon         https://arxiv.org/favicon.ico
// @grant        none
// @license      AGPL License
// ==/UserScript==


//原作者的CSS选择器有点问题。
//建议装上SelectorGadget浏览器扩展,直接边调试边改代码。



(function() {
    'use strict';
    const url = location.pathname,webTitle = document.title
    var downloadName = '',downloadPath = ''
    var papertitle = '',papertime = ''
    if(url.search('/abs/')!=-1){
        papertitle = document.querySelector("#abs > h1").innerText
        downloadPath = document.querySelector(".download-pdf")
        papertime = document.querySelector(".dateline").innerText.replace("[Submitted on ","").replace("]","")
        downloadName = renamePaperFile(papertitle,papertime)
        addDownloadButton(downloadPath,downloadName,document.querySelector("#abs-outer > div.extra-services > div.full-text"))
    }
    if(url.search('/search/')!=-1){
        var paperlist = document.querySelectorAll("#main-container > div.content > ol > li")
        for(let paper in paperlist){
            papertitle = paperlist[paper].children[1].innerText
            papertime = paperlist[paper].querySelector("p.is-size-7").innerText.split(";")[0].replace("Submitted ","")
            downloadName = renamePaperFile(papertitle,papertime)
            downloadPath = paperlist[paper].children[0].children[0].children[1].children[0].href+'.pdf'
            addDownloadButton(downloadPath,downloadName,paperlist[paper].children[0])
        }
    }

    function addDownloadButton(downloadPath,downloadName,element){
        var button = document.createElement("a"); //创建一个input对象(提示框按钮)
        button.id = "downloadPaper";
        button.textContent = "下载论文(重命名)";
        button.setAttribute("href", downloadPath)
        button.setAttribute("download", downloadName)
        element.append(button);
    }
    function renamePaperFile(name,time){
        var downloadName = name.replace(': ',':')
        downloadName = downloadName.replace(':',':')
        downloadName = downloadName.replace('?','?')
        downloadName = downloadName.replace('/',' OR ')
        downloadName = downloadName.replace('"','“')+'.pdf'
        return '['+time+']'+downloadName
    }
})();