youtube-dl只接收网址的第一个字母?

时间:2017-09-23 18:29:56

标签: python-3.x url youtube youtube-dl

的StackOverflow!

我在使用youtube-dl时遇到了一些问题。我最近有这个工作,但我做了一些改变,现在它拒绝工作。这是我的代码:

import youtube_dl
import os

class InvalidURL(Exception):
    pass

class SongExists(Exception):
    pass

def download(url):
    try:
        options = {
            'format': 'bestaudio/best',
            'quiet': False,
            'extractaudio': True,  # only keep the audio
            'audioformat': "wav",  # convert to wav
            'outtmpl': '%(id)s.wav',  # name the file the ID of the video
            'noplaylist': True,  # only download single song, not playlist
        }
        with youtube_dl.YoutubeDL(options) as ydl:
            r = ydl.extract_info(url ,download=False)
            if os.path.isfile(str(r["id"])):
                raise SongExists('This song has already been requested.')
            print("Downloading", r["title"])
            print(str(url))
            ydl.download(url)
            print("Downloaded", r["title"])
            return r["title"], r["id"]
    except youtube_dl.utils.DownloadError:
        raise InvalidURL('This URL is invalid.')

if __name__ == "__main__":
    download("https://www.youtube.com/watch?v=nvHyII4Dq-A")

据我所知,我的脚本似乎是从我的网址中取出第一个字母。有谁知道为什么?作为" Side-quest",是否有人知道如何搜索而不是网址?

这是我的输出:

[youtube] nvHyII4Dq-A: Downloading webpage
[youtube] nvHyII4Dq-A: Downloading video info webpage
[youtube] nvHyII4Dq-A: Extracting video information
WARNING: unable to extract uploader nickname
[youtube] nvHyII4Dq-A: Downloading MPD manifest
Downloading MagnusTheMagnus - Area
https://www.youtube.com/watch?v=nvHyII4Dq-A
ERROR: 'h' is not a valid URL. Set --default-search "ytsearch" (or run  youtube-dl "ytsearch:h" ) to search YouTube
Traceback (most recent call last):
  File "C:\Users\tyler\AppData\Local\Programs\Python\Python36-32\lib\site-packages\youtube_dl\YoutubeDL.py", line 776, in extract_info
    ie_result = ie.extract(url)
  File "C:\Users\tyler\AppData\Local\Programs\Python\Python36-32\lib\site-packages\youtube_dl\extractor\common.py", line 433, in extract
    ie_result = self._real_extract(url)
  File "C:\Users\tyler\AppData\Local\Programs\Python\Python36-32\lib\site-packages\youtube_dl\extractor\generic.py", line 1993, in _real_extract
    % (url, url), expected=True)
youtube_dl.utils.ExtractorError: 'h' is not a valid URL. Set --default-search "ytsearch" (or run  youtube-dl "ytsearch:h" ) to search YouTube

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/tyler/PycharmProjects/PythonSpeakerThing/downloader.py", line 26, in download
    ydl.download(url)
  File "C:\Users\tyler\AppData\Local\Programs\Python\Python36-32\lib\site-packages\youtube_dl\YoutubeDL.py", line 1958, in download
    url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  File "C:\Users\tyler\AppData\Local\Programs\Python\Python36-32\lib\site-packages\youtube_dl\YoutubeDL.py", line 799, in extract_info
    self.report_error(compat_str(e), e.format_traceback())
  File "C:\Users\tyler\AppData\Local\Programs\Python\Python36-32\lib\site-packages\youtube_dl\YoutubeDL.py", line 604, in report_error
    self.trouble(error_message, tb)
  File "C:\Users\tyler\AppData\Local\Programs\Python\Python36-32\lib\site-packages\youtube_dl\YoutubeDL.py", line 574, in trouble
    raise DownloadError(message, exc_info)
youtube_dl.utils.DownloadError: ERROR: 'h' is not a valid URL. Set --default-search "ytsearch" (or run  youtube-dl "ytsearch:h" ) to search YouTube

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/tyler/PycharmProjects/PythonSpeakerThing/downloader.py", line 33, in <module>
    download("https://www.youtube.com/watch?v=nvHyII4Dq-A")
  File "C:/Users/tyler/PycharmProjects/PythonSpeakerThing/downloader.py", line 30, in download
    raise InvalidURL('This URL is invalid.')
__main__.InvalidURL: This URL is invalid.

2 个答案:

答案 0 :(得分:4)

作为documentedydl.download功能会获取网址的列表。而不是

ydl.download(url)

你想打电话

ydl.download([url])

要运行搜索,首先要运行youtube-dl --extractor-descriptions | grep search来查找关键字。例如,Soundcloud搜索的关键字为scsearch,YouTube默认搜索的关键字为ytsearch

然后,只需传递关键字和搜索字词,以冒号(:)分隔,作为网址。

例如,ytsearch:fluffy bunnies的网址会在YouTube上找到使用默认搜索条件的蓬松兔子的顶级视频。

答案 1 :(得分:1)

以下是示例:

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import androidx.annotation.RequiresPermission
import androidx.core.content.ContextCompat

object PowerSaverHelper {
    enum class WhiteListedInBatteryOptimizations {
        WHITE_LISTED, NOT_WHITE_LISTED, ERROR_GETTING_STATE, IRRELEVANT_OLD_ANDROID_API
    }

    fun getIfAppIsWhiteListedFromBatteryOptimizations(context: Context, packageName: String = context.packageName): WhiteListedInBatteryOptimizations {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return WhiteListedInBatteryOptimizations.IRRELEVANT_OLD_ANDROID_API
        val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager?
                ?: return WhiteListedInBatteryOptimizations.ERROR_GETTING_STATE
        return if (pm.isIgnoringBatteryOptimizations(packageName)) WhiteListedInBatteryOptimizations.WHITE_LISTED else WhiteListedInBatteryOptimizations.NOT_WHITE_LISTED
    }

    //@TargetApi(VERSION_CODES.M)
    @SuppressLint("BatteryLife", "InlinedApi")
    @RequiresPermission(Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
    fun prepareIntentForWhiteListingOfBatteryOptimization(context: Context, packageName: String = context.packageName, alsoWhenWhiteListed: Boolean = false): Intent? {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return null
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) == PackageManager.PERMISSION_DENIED)
            return null
        val appIsWhiteListedFromPowerSave: WhiteListedInBatteryOptimizations = getIfAppIsWhiteListedFromBatteryOptimizations(context, packageName)
        var intent: Intent? = null
        when (appIsWhiteListedFromPowerSave) {
            WhiteListedInBatteryOptimizations.WHITE_LISTED -> if (alsoWhenWhiteListed) intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
            WhiteListedInBatteryOptimizations.NOT_WHITE_LISTED -> intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).setData(Uri.parse("package:$packageName"))
            WhiteListedInBatteryOptimizations.ERROR_GETTING_STATE, WhiteListedInBatteryOptimizations.IRRELEVANT_OLD_ANDROID_API -> {
            }
        }
        return intent
    }
}