python - 如何使用 Python 从 csv 文件中抓取 YouTube URL 列表并输出到新的 csv 文件

标签 python web-scraping beautifulsoup youtube

我正在抓取多个 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 文件中。

最佳答案

我会回应克劳斯的说法。这些人会尽一切努力阻止您进行这些大数据转储。正如您所看到的,它对于一个 URL 来说工作得很好,但是 Google 工程师当然拥有适当的工具来防止重复调用他们的系统。你可以寻找一个 API,如果允许的话,它可以很容易地做到这一点。或者,输入访问网站的时间,例如每 30-60 秒 1 次,或其他。也许您可以将其设置为在出去办事之前或 sleep 之前运行。如果每 60 秒 1x,则只需 2.5 小时即可完成这项工作。只是一个想法。

import time
while True:
    print("This prints once a minute.")
    time.sleep(60)

将其放在第一个 for 循环之前,看看它是否符合您的要求。他们可以轻松计算每个时间段每个 IP 地址的请求数量,并拒绝任何超过指定限制的请求,因此这个概念可能有效,也可能无效。此外,您可能需要确保没有违反 YouTube 使用条款和条件。

关于python - 如何使用 Python 从 csv 文件中抓取 YouTube URL 列表并输出到新的 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57147613/

相关文章:

从 HTML 中提取 Python 脚本

python - 如何在 EC2 linux 环境中降级我的 BeautifulSoup 版本?

python - 在 python 中使用 jinja2 连接字符串和数字

python - 通过 "0"和 Slack API 将 `slacker` 发布到 Slack channel

python - 抓取图片url src时,获取数据:image/jpeg;base64

python - 重新格式化已删除的 Selenium 表

python - 使用Scrapy抓取数据

python - 如何循环 python 读取一组 HTML 文件并转储到 JSON

python - 如何在 Python 中将 float 转换为 10 次方的科学记数法?

python - Gecko驱动问题