抓取所有youtube搜索结果

时间:2019-11-02 22:28:03

标签: python-3.x selenium web-scraping youtube

我正在尝试从youtube搜索结果中收集数据。搜索字词是“边境牧羊犬” ,其中包含对“今天” 上传的视频的过滤器。

52个视频出现在搜索结果中。但是,当我尝试解析页面时,我只有20个条目。如何解析所有52个视频?任何建议表示赞赏。

P.S。我在不定式页面上尝试了此post,但不适用于youtube。

当前代码:

url = 'https://www.youtube.com/results?search_query=border+collie&sp=EgIIAg%253D%253D'
driver = webdriver.Chrome()
driver.get(url)

#waiting for the page to load
sleep(3) 
#repeat scrolling 10 times
for i in range(10):
    #scroll 1000 px
    driver.execute_script('window.scrollTo(0,(window.pageYOffset+1000))')
    sleep(3) 

response = requests.get(url)
soup = bs(response.text,'html.parser',from_encoding="UTF-8")

source_list = []
duration_list = []

#Scrape source of the video
vids_source = soup.findAll('div',attrs={'class':'yt-lockup-byline'})
for i in vids_source:
    source = i.text
    source_list.append(source)

#Scrape video duration
vids_badge = soup.findAll('span',attrs={'class':'video-time'})
for i in vids_badge:
    duration = i.text
    duration_list.append(duration)

1 个答案:

答案 0 :(得分:1)

我认为您在混淆requestsselenium。请求模块可用于下载和抓取,而无需使用浏览器。根据您的要求,要向下滚动并获得更多结果,请单独使用Selenium并使用XPATH之类的DOM定位器抓取结果。

source_list = []
duration_list = []
for i in range(10):
    #scroll 1000 px
    driver.execute_script('window.scrollTo(0,(window.pageYOffset+1000))')
    sleep(3)
    elements = driver.find_elements_by_xpath('//div[@class = "yt-lockup-byline"]')
    for element in elements:
        source_list.append(element.text)
    elements = driver.find_elements_by_xpath('//span[@class = "video-time"]')
    for element in elements:
        duration_list.append(element.text)

因此,我们首先滚动并获取所有元素文本。再次滚动并再次获取所有元素,依此类推。如此刮取时无需使用requests

相关问题