如何使用请求向下滚动youtube视频

2024-04-26 20:30:23 发布

您现在位置:Python中文网/ 问答频道 /正文

下面几节代码可以工作,但问题是它只获取页面可见部分的视频名称。我想做的是向下滚动页面。有没有一种方法可以在python中使用requests模块向下滚动??在

    def __init__(self):
    word = input("Search: ")
    self.r = requests.get('https://www.youtube.com/results?search_query={}'.format(word))
    self.soup = BeautifulSoup(self.r.content,"html.parser")

def find_video(self):
    videos = self.soup.find('div',attrs={"id":"content"}).find_all("div",attrs={"class":"yt-lockup-content"})
    for video in videos:
        user_detector = video.a.get("href")
        if user_detector.startswith("/watch"):
            print(video.a.text)
            print("------------------------------------")
        else:
            pass

Tags: selfdivgetdefvideo页面contentfind
2条回答

由于您没有使用官方API,所以不能通过使用requests/BeautifulSoup来实现。您需要执行Javascript才能实现这一点。在

我的建议是使用一个与浏览器直接交互并能够执行JS的webdriver。在

from selenium import webdriver
import time
bot = webdriver.Firefox()
url = 'https://www.youtube.com/results?search_query={}'.format(word)
bot.get(url)
#waiting for the page to load
time.sleep(3) 
#repeat scrolling 10 times
for i in range(10):
    #scroll 300 px
    bot.execute_script('window.scrollTo(0,(window.pageYOffset+300))')
    #waiting for the page to load
    time.sleep(3) 

请求不解释JavaScript。如果您想拥有和使用浏览器相同的行为,就必须使用Selenium。页面上的内容是通过ajax动态加载的。因此,请求不利于此。在

相关问题 更多 >