一到两周前,我开始学习用python编写代码。我想要创建的东西,你会键入一些歌曲的名称,然后程序将返回搜索页面链接和歌曲链接(灵感来自一个机器人的不和谐)。我得到了第一部分的工作,搜索页的链接会返回很好,但我不知道如何链接这首歌。所以我想,如果我能打印出第一个弹出的视频标题,我会没事的,因为大多数情况下,第一个链接是一个理想的。所以我制作了一个爬虫来抓取视频的所有链接,然后我会返回第一个链接。这部分不能用..。然而,相同的爬虫代码适用于其他网站。我搞不懂这个..。
from bs4 import BeautifulSoup
import requests
import urllib
def milo():
User_input = input("Title of Youtube vid - ")
words = User_input.split()
list = []
list.append('+'.join(words))
print("https://www.youtube.com/results?search_query=" + list[0])
url = "https://www.youtube.com/results?search_query=" + list[0]
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')
for link in soup.findAll('a',"video-title"):
song = link.get('href')
list.append('https://www.youtube.com' + song)
print(list[0])
milo()发布于 2018-06-12 11:21:09
不要使用变量list,因为这是一个保留的python,而不是这个,您可以使用lst并尝试这样做,这样就可以了
# lst instead of list
lst = []
...
for link in soup.findAll('a',{'class':'yt-uix-tile-link'}):
lst.append('https://www.youtube.com' + link.get('href'))
print(lst)
# if in inspect document don't find any of .class or #id for any of tags
# we need to get a `tag` that we need for example in our case it is `a`
# and after find our tag that we need and there will be all classes and tags that we need
# bacause for example youtube make some tags hidden and we don't we it with inspect from chrome/firefox
for link in soup.findAll('a'):
print(link)输出
Title of Youtube vid - Roots
https://www.youtube.com/results?search_query=Roots
[
'Roots', 'https://www.youtube.com/watch?v=PUdyuKaGQd4',
# many other urls
...
'https://www.youtube.com/watch?v=eB4oFu4BtQ8'
]https://stackoverflow.com/questions/50815027
复制相似问题