Youtube API使用proxy代理
通过YouTube API,我们可以轻松获取YouTube播放列表、视频和分类等信息。不过前提是首先先申请一个DEVELOPER_KEY,申请地址:https://console.cloud.google.com/apis/credentials。
不过,在国内并不能直接连接YouTube,也不能直接连接YouTube API。下面以获取视频信息为例,代码:
from googleapiclient.discovery import build YOUTUBE_DEVELOPER_KEY = '填入自己的DEVELOPER_KEY' YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=YOUTUBE_DEVELOPER_KEY) result = youtube.videos().list( part="snippet", id="HtSuA80QTyo" ).execute() print(result)
上面是不使用proxy的方法,用proxy有两种方式:
方式一 指定http
参数
from googleapiclient.discovery import build import httplib2 from httplib2 import socks YOUTUBE_DEVELOPER_KEY = '填入自己的DEVELOPER_KEY' YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' # 如下是代理设置 proxy_info = httplib2.ProxyInfo(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 1080) http = httplib2.Http(timeout=config.youtube_api_timeout, proxy_info=proxy_info) # 构建youtube对象时增加http参数 youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=YOUTUBE_DEVELOPER_KEY, http=http) result = youtube.videos().list( part="snippet", id="HtSuA80QTyo" ).execute() print(result)
方法二 设置socket代理
from httplib2 import socks import socket from googleapiclient.discovery import build # 设置socket代理,相当于底层使用了代理,不需要在youtube参数再设置 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 1080) socket.socket = socks.socksocket YOUTUBE_DEVELOPER_KEY = '填入自己的DEVELOPER_KEY' YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=YOUTUBE_DEVELOPER_KEY) result = youtube.videos().list( part="snippet", id="HtSuA80QTyo" ).execute() print(result)