Python 爬取網易雲音樂 自動安裝所需模組

Melody Knit發表於2020-10-04

Python爬取網易雲音樂 自動安裝所需模組

話不多說上程式碼把

# 利用try檢查以下模組是否有未安裝的,如有未安裝的會執行except進行安裝
try:
    if __name__ == '__main__':
        from os.path import dirname
        from requests import get
        from time import sleep
        from re import sub

        class Music:
            def __init__(self):
                self.id = int
                self.url = str
                self.out = 10
                self.main_url = str
                self.file_name = None
                self.music_163 = 'http://music.163.com/song/media/outer/url'
                self.headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"}

            def save(self):
                mp3 = get(self.url, headers=self.headers)
                self.file_name = self.id
                if 'y' in input('是否需要更改檔名請輸入yes或no\n> '):
                    self.file_name = input('請輸入名字> ')
                with open(f'{self.file_name}.mp3', 'ab') as file:
                    file.write(mp3.content)
                    file.flush()

            def url_split(self):
                return int(sub(r"\D", "", self.main_url.split('song')[1]))

            @staticmethod
            def input_url():
                return input("爬取網易雲音樂地址\n> ")

            def run(self):
                self.main_url = self.input_url()
                if 'music.163.com' in self.main_url:
                    self.id = self.url_split()
                    self.url = f'{self.music_163}?id={self.id}.mp3'
                    self.save()
                print(f'儲存成功,檔名為"{self.file_name}.mp3"')
                print(f'{self.out}秒後推出此頁面')
                sleep(self.out)
        music = Music()
        music.run()

except ModuleNotFoundError as error:
    print(f'安裝"{error.name}"庫')
    try:
        from os import system
        system(f'pip install {error.name}')
        system(f'python {__file__}')
    except Exception as error:
        print(f'\033[0;31m{error} \033[0m!')


相關文章