为了账号安全,请及时绑定邮箱和手机立即绑定

Python Youtube Web Scraper 无法正常工作

Python Youtube Web Scraper 无法正常工作

慕标琳琳 2023-03-08 15:34:27
所以我构建了这个小脚本,可以返回 YouTube 上任何搜索到的视频的 URL。但是在再次打开它之后发现使用 youtube 进行的网络抓取无法正常工作。在打印时,soup它返回的内容与在 Youtube 上使用 inspect element 看到的内容完全不同。有人能帮我解决这个问题吗……这是我的代码:import requestsfrom lxml import htmlimport webbrowserfrom bs4 import BeautifulSoupimport timeimport tkinterfrom pytube import YouTubeheaders= {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36"}def video_finder():    word = input("Enter video title: ")    if ' ' in word:        new = word.replace(' ', '+')        print(new)    else:        pass    vid = requests.get('https://www.youtube.com/results?search_query={}'.format(new))    soup = BeautifulSoup(vid.text, features='lxml')    all_vids = soup.find_all('div', id_='contents')    print(all_vids)    video1st = all_vids[0]    a_Tag = video1st.find('a', class_="yt-uix-tile-link yt-ui-ellipsis yt-ui-ellipsis-2 yt-uix-sessionlink spf-link", href=True)    Video_name = a_Tag.text    Video_id = a_Tag['href']    video_link = 'https://www.youtube.com' + Video_id    print(Video_name)    print(video_link)它不是最好的但是你...谢谢
查看完整描述

1 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

要从 Youtube 页面获得正确的结果,请将User-AgentHTTP 标头设置为 Googlebot,并 html.parser在 BeautifulSoup 中使用。


例如:


import requests

from bs4 import BeautifulSoup



headers= {"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}

def video_finder():

    word = input("Enter video title: ")


    params = {

        'search_query': word

    }


    vid = requests.get('https://www.youtube.com/results', params=params, headers=headers)

    soup = BeautifulSoup(vid.content, features='html.parser')

    a_Tag = soup.find('a', class_="yt-uix-tile-link yt-ui-ellipsis yt-ui-ellipsis-2 yt-uix-sessionlink spf-link", href=lambda h: h.startswith('/watch?'))

    Video_name = a_Tag.text

    Video_id = a_Tag['href']

    video_link = 'https://www.youtube.com' + Video_id

    print(Video_name)

    print(video_link)


video_finder()

印刷:


Enter video title: sailor moon

Sailor Moon Opening (English) *HD*

https://www.youtube.com/watch?v=5txHGxJRwtQ


查看完整回答
反对 回复 2023-03-08
  • 1 回答
  • 0 关注
  • 149 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号