python - 编码问题-Python

标签 python youtube soundcloud

我正在编写一个程序,以读取mysql表中的歌曲并在youtube上找到歌曲。我想下载歌曲并将其放在我的soundcloud帐户中。我试图为此编写代码。问题是,每次运行它都会遇到以下问题:
Non-ASCII character '\xe2' in file on line 164, but no encoding declared
请帮助解决相同的问题。

import youtube_dl

from apiclient.discovery import build
from apiclient.errors import HttpError

import sys
import pymysql
import urllib2
import urllib 
from urllib import urlopen
import json
import soundcloud
from goto import goto, label
import time


DEVELOPER_KEY = ""
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

global conn
conn=pymysql.connect(db='twitter_users', user='root' , host='127.0.0.1' , port=3307)
global cursor
cursor=conn.cursor()
client = soundcloud.Client(client_id= '',
                           client_secret= '',
                           username= '',
                           password= '' )
global song_name
global artist_final
global stored_title   
global genre 
def search_video(title):
  search_response = youtube.search().list(
    q=title,
    part="id,snippet",
    maxResults=10
  ).execute()

  for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
        return search_result["id"]["videoId"], search_result["snippet"]["title"]


##youtube_dl configuration
class MyLogger(object):
    def debug(self, msg):
        pass

    def warning(self, msg):
        pass

    def error(self, msg):
        print(msg)

def my_hook(d):
    if d['status'] == 'downloading':
        sys.stdout.write('\r\033[K')
        sys.stdout.write('\tDownloading... ETA: ' + str(d["eta"]) + " seconds")
        sys.stdout.flush()
    elif d['status'] == 'finished':
        sys.stdout.write('\r\033[K')
        sys.stdout.write('\tDownload complete\n\tConverting video to mp3')
        sys.stdout.flush()

ydl_opts = {
    'format': 'bestaudio',
    'outtmpl': '%(title)s.%(ext)s',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '0',
    }],
    'logger': MyLogger(),
    'progress_hooks': [my_hook],
}


##main
label .start
if __name__ == "__main__":
    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,developerKey=DEVELOPER_KEY)
    query=cursor.execute("select search_term from song_downloads where Soundcloud_TID='' order by id asc limit 1")
    if query>0:
        query_result=cursor.fetchone()
        term=query_result[0]
    else:
        goto .end    
    print("\tSearching video")
    try:
        videoID, videoTitle = search_video(term);
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            print("\tFound video: '" + videoTitle + "' - ID: " + videoID)
            Find=cursor.execute("select Youtube_VID from song_downloads where Youtube_VID=%s", (videoID))
            if find>0:
                goto .duplicate
            else:
                try:
                    song_name=videoTitle.split(' - ')[1]
                except:
                    song_name='Null'
                try:    
                    Artist_name=videoTitle.split(' - ')[0]       
                    if ' feat. ' in Artist_name:
                        artist_final=Artist_name.split(' feat. ')[0]
                    elif ' feat ' in Artist_name:
                        artist_final=Artist_name.split(' feat ')[0]
                    elif ' ft ' in Artist_name:
                        artist_final=Artist_name.split(' ft ')[0]
                    elif ' ft. ' in Artist_name:
                        artist_final=Artist_name.split(' ft. ')[0]
                    elif ' featuring ' in Artist_name:
                        artist_final=Artist_name.split(' featuring ')[0]
                    elif ' Starring ' in Artist_name:
                        artist_final=Artist_name.split(' Starring ')[0]
                    elif ' Feat ' in Artist_name:
                        artist_final=Artist_name.split(' Feat ')[0]
                    elif ' Feat. ' in Artist_name:
                        artist_final=Artist_name.split(' Feat.')[0]
                    elif ' Featuring ' in Artist_name:
                        artist_final=Artist_name.split(' Featuring ')[0]
                    elif ' Ft. ' in Artist_name:
                        artist_final=Artist_name.split(' Ft. ')[0]
                    elif ' starring ' in Artist_name:
                        artist_final=Artist_name.split(' starring ')[0]   
                    else:
                        artist_final=Artist_name
                except:
                    artist_final='Null'       
                if artist_final=='Null':
                    genre='Null'
                else:
                    try:     
                        api_beg='http://developer.echonest.com/api/v4/artist/profile?api_key=OZ8G9N2O7YFPZIRXN&'
                        api_end='&bucket=genre&format=json'
                        api_final=api_beg+'name='+artist_final+api_end
                        url= urlopen(api_final).read()
                        print('url read')
                        result=json.loads(url)
                        print('result decoded')
                        genre= result['response']['artist']['genres'][0]['name']
                    except:
                        genre='Null'
                if artist_final=='Null':
                    album_art='Null'             
                else:
                    try:       
                        api_image_beg='http://developer.echonest.com/api/v4/song/search?api_key=OZ8G9N2O7YFPZIRXN&format=json&results=1&artist='
                        api_image_end='&bucket=id:7digital-US&bucket=tracks'
                        api_image_final=api_image_beg+artist_final+'&title='+song_name+api_image_end
                        url= urlopen(api_image_final).read()
                        result=json.loads(url)
                        album_art=result['response']['songs'][0]['tracks'][0]['release_image']
                        print(album_art)
                    except:
                        album_art='Null'            
                print(artist_final)
                print(genre)       
                ydl.download(['http://www.youtube.com/watch?v=' + videoID])
                print("\tDone")
                stored_title=videoTitle + '.mp3'
                cursor.execute("update song_downloads set Song_Name=%s , Artist_Name=%s, Genre=%s, Album_art_url=%s, Youtube_VID=%s, video_title=%s where Search_Term=%s" , (song_name.encode('utf-8'), artist_final('utf-8'), genre.encode('utf-8'),album_art.encode(‘utf-8’),videoID.encode('utf-8'),stored_title.encode('utf-8'), term.encode('utf-8')))
                conn.commit()



track = client.post('/tracks', track={
    'title': song_name + '-' artist_final,
    'genre': genre,
    'artwork_data':album_art,
    'asset_data': open(stored_title, 'rb')
})

soundcloud_track_url=track.permalink_url
cursor.execute("update song_downloads set Soundcloud_TID=%s where Youtube_VID=%s" , (soundcloud_track_url.encode('utf-8'),videoID.encode('utf-8')))
conn.commit()
print("Track downloaded and posted to SC")
label .duplicate
cursor.execute("update song_downloads set Youtube_VID='duplicate' where Search_Term=%s " , (term))
label .end
print("sleep for 1 minute")
time.sleep(60)
goto .start


    except HttpError, e:
        print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)      

最佳答案

您在此处使用了错误的引号:
换线164

album_art.encode('utf-8'),-> album_art.encode('utf-8'),

如果使用十六进制编辑器,则可以搜索char 0xe2并将其替换为0x27。

关于python - 编码问题-Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32382879/

相关文章:

python - 将 gmail 时间戳转换为 strptime

python - 如果满足特定条件如何删除行(Python)

xml-parsing - 来自YouTube的警告simplexml_load_file解析器错误

iphone - 将视频从 youtube 应用分享到我在 ios 上的应用

javascript - 从外部脚本中的函数捕获错误

facebook-graph-api - 将音频文件上传到 Facebook

javascript - SoundCloud Api - 如何制作(设置)播放列表收藏夹?

python - Pandas 选择不连续的数据框日期切片?

python - Matplotlib:如何制作由点(圆圈)组成的虚线?

flash - 在Samsung Smart TV App中显示Youtube视频