首页 > 解决方案 > 用于搜索 Youtube 视频的 Python 文本源代码

问题描述

Python Noob在这里,

这段代码的作用是打印并在 youtube 中打开所有 url。

我只是希望它打开它找到的第一个 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

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

标签: python-3.xurlyoutube

解决方案


基于 BeautifulSoup 的文档

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

只需添加

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

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

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

推荐阅读