Python 用于搜索 Youtube 视频的文本源代码

Python Text to Search for Youtube videos Source Code

Python 菜鸟,

此代码的作用是打印并在 youtube 中打开所有 urls。

我只希望它打开它找到的第一个 url 而不是所有这些。

import urllib.request

from bs4 import BeautifulSoup

import webbrowser

textToSearch = 'Hello World'
query = urllib.parse.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib.request.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
    print('https://www.youtube.com' + vid['href'])
    url = ('https://www.youtube.com/' + vid['href'])
    webbrowser.open(url)
    print('Done!')

我想到了换行

soup.findAll

soup.find

但它不起作用:

TypeError: string indices must be integers

而且我不知道该怎么做,这一定很简单,我没有太多知识,所以如果你能帮助我,我真的很感激

基于 BeautifulSoup

的文档

https://www.crummy.com/software/BeautifulSoup/bs4/doc/

只需添加

for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}, limit=1):

所以您将 return 第一个。 我认为 find 不起作用,因为使用这些参数 vid 变成了一个字符串,在 python 中你不能做

vid='whatever'
print vid['href']