python-3.x - 用于搜索 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
而且我不知道该怎么做,它一定很简单,而且我没有太多知识,所以如果你能帮助我,我真的很感激
解决方案
基于 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']
推荐阅读
- python - pandas数据框中的lambda函数中的多个条件
- javascript - 如何使用 JavaScript 添加 (F1) 键功能
- java - 如何使 if 语句重复到特定数组而不是所有程序
- python - pymc3 中的贝叶斯更新:添加更多数据不起作用
- mapbox-gl-js - 如何在 Mapbox GL JS 中更改光标图像
- xcode - 打开存储在 GitLab 中的旧版本 Xcode 项目文件
- swift - 一个按钮卡在同一个位置 - swift
- bigcommerce - 如何在 bigcommerce 的结帐 SDK 中获取税率
- html - 我不知道如何使用 CSS 和 HTML 将每个 div 元素的单词放在每一侧的中间
- azure - 为什么 Azure 数据工厂中默认自动创建的 sql 表列长度为 -1?以及如何修复它?