Python Noob在这里,
此代码的作用是打印并在youtube中打开所有网址。
我只希望它打开找到的第一个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'}
,限制= 1):
因此您将返回第一个。
查找不起作用,我认为是因为使用这些参数,vid变成了字符串,而在python中您无法执行
vid='whatever'
print vid['href']
关于python-3.x - 使用Python文本搜索YouTube视频源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54973526/