【发布时间】:2019-07-22 13:55:48
【问题描述】:
我正在抓取多个 YouTube 视频,并希望能够一次抓取它们并将视频加载到一个带有抓取时间时间戳的 csv 文件中,这样我就可以重复该过程并查看随时间的变化下面列出的指标。
这是我正在使用的教程 - https://www.promptcloud.com/blog/how-to-scrape-youtube-data-using-python/
我一直在尝试遵循其他建议,包括使用 Python 自己的 url 功能解析 url 以及使用 pandas 作为数据框来从中导入 url。没有一个工作。
下面是我使用的代码。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib.request
import urllib.parse
import urllib.error
from bs4 import BeautifulSoup
import ssl
import json
import ast
import json
import os
from urllib.request import Request, urlopen
# For ignoring SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# Input from user
url = '[INSERT YOUTUBE VIDEO URL]'
# Making the website believe that you are accessing it using a mozilla browser
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()
# Creating a BeautifulSoup object of the html page for easy extraction of data.
soup = BeautifulSoup(webpage, 'html.parser')
html = soup.prettify('utf-8')
video_details = {}
other_details = {}
for span in soup.findAll('span',attrs={'class': 'watch-title'}):
video_details['TITLE'] = span.text.strip()
for script in soup.findAll('script',attrs={'type': 'application/ld+json'}):
channelDesctiption = json.loads(script.text.strip())
video_details['CHANNEL_NAME'] = channelDesctiption['itemListElement'][0]['item']['name']
for div in soup.findAll('div',attrs={'class': 'watch-view-count'}):
video_details['NUMBER_OF_VIEWS'] = div.text.strip()
for button in soup.findAll('button',attrs={'title': 'I like this'}):
video_details['LIKES'] = button.text.strip()
for button in soup.findAll('button',attrs={'title': 'I dislike this'}):
video_details['DISLIKES'] = button.text.strip()
for span in soup.findAll('span',attrs={'class': 'yt-subscription-button-subscriber-count-branded-horizontal yt-subscriber-count'}):
video_details['NUMBER_OF_SUBSCRIPTIONS'] = span.text.strip()
hashtags = []
for span in soup.findAll('span',attrs={'class': 'standalone-collection-badge-renderer-text'}):
for a in span.findAll('a',attrs={'class': 'yt-uix-sessionlink'}):
hashtags.append(a.text.strip())
video_details['HASH_TAGS'] = hashtags
with open('output_file.html', 'wb') as file:
file.write(html)
with open('data.json', 'w', encoding='utf8') as outfile:
json.dump(video_details, outfile, ensure_ascii=False,indent=4)
print ('----------Extraction of data is complete. Check json file.----------')
我希望能够一次抓取大约 150 个 YouTube 视频(作为列表包含在 csv 列中)并将结果输出到 csv 而不是 json 文件。
【问题讨论】:
-
长话短说:一般来说,Youtube 和 Google 不喜欢被抓取。他们有措施来应对它。不要指望任何教程永远有效。
-
感谢@KlausD。我怀疑这一点,但我对编码很陌生 - 所以有点希望!它适用于一个 url,有没有办法让它自动适用于我在 csv 中的 url 列表?
标签: python web-scraping beautifulsoup youtube