首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >网络爬虫没有在Youtube上工作

网络爬虫没有在Youtube上工作
EN

Stack Overflow用户
提问于 2018-06-12 10:32:08
回答 1查看 993关注 0票数 1

一到两周前,我开始学习用python编写代码。我想要创建的东西,你会键入一些歌曲的名称,然后程序将返回搜索页面链接和歌曲链接(灵感来自一个机器人的不和谐)。我得到了第一部分的工作,搜索页的链接会返回很好,但我不知道如何链接这首歌。所以我想,如果我能打印出第一个弹出的视频标题,我会没事的,因为大多数情况下,第一个链接是一个理想的。所以我制作了一个爬虫来抓取视频的所有链接,然后我会返回第一个链接。这部分不能用..。然而,相同的爬虫代码适用于其他网站。我搞不懂这个..。

代码语言:javascript
复制
    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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-12 11:21:09

不要使用变量list,因为这是一个保留的python,而不是这个,您可以使用lst并尝试这样做,这样就可以了

代码语言:javascript
复制
# 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)

输出

代码语言:javascript
复制
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'
]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50815027

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档