Python:urlib.request.urlopen工作不正常



我不知道为什么这段代码不起作用。当我打印列表";视频";以及";搜索结果";看看发生了什么,他们都是空的。这就是为什么从未到达if语句的原因,正如您在屏幕截图中看到的那样。

# Query youtube results based on the songs entered in the text file
def find_video_urls(self, songs):
videos = list()
for song in songs:
self.update_text_widget("nSong - " + song + " - Querying youtube results ...")

query_string = urllib.parse.urlencode({"search_query": song})
with urllib.request.urlopen("http://www.youtube.com/results?" + query_string) as html_content:
# retrieve all videos that met the song name criteria
search_results = re.findall(r'href="/watch?v=(.{11})', html_content.read().decode())
# only take the top result
if len(search_results) != 0:
videos.append("https://www.youtube.com/watch?v=" + search_results[0])
self.update_text_widget("nSong - " + song + " - Found top result!")
return videos

GUI输出

Hi-Vigilante我将分享一段关于如何处理请求的代码。也许你可以在你的代码中实现它。

import re
import requests
def find_video_urls(songs):
videos = list()
for song in songs:
with requests.session() as ses:
r = ses.get('http://www.youtube.com/results', params={"search_query": song})
search_results = re.findall(b'(/watch?v=.{11})"', r.content, re.MULTILINE | re.IGNORECASE | re.DOTALL)
print(search_results)

# only take the top result
if len(search_results) != 0:
videos.append(b"".join([b'https://www.youtube.com', search_results[0]]))
return videos
print(find_video_urls(['Eminem - Lose Yourself']))

最新更新