zh
English
Español
Tiếng Việt
Deutsch
Українська
Português
Français
भारतीय
Türkçe
한국인
Italiano
Gaeilge
اردو
Indonesia
Polski YouTube 内容创作者必须分析每个视频的表现,包括分析评论以及创作者自己的内容与相同或不同类别的其他视频的关系。
手动查看所有视频可能会让人疲惫不堪,也很困难。在这种情况下,一个特殊的脚本就会派上用场。在本指南中,我们将向你展示如何刮取 YouTube 并创建这样一个脚本,旨在将通常手动进行的数据收集过程自动化。
在了解如何搜索 YouTube 之前,我们需要先了解它的结构。它有许多可用的功能,有无穷无尽的数据类型可供选择,涉及用户活动和视频统计。该平台的一些关键参数包括视频标题和描述、添加的标签、浏览量、点赞和评论,以及频道和播放列表信息。这些元素对于内容营销人员和创作者评估视频的表现以及制定视频内容的策略非常重要。
利用 YouTube 数据 API,开发人员可以通过编程方式访问大部分指标。该 API 还允许访问订阅者数量以及频道上的视频,从而为分析和整合目的提供大量数据。
然而,有些特定元素可能无法通过应用程序接口获取,因此只能通过网络搜刮来检索。例如,要获得某些详细的观众参与度指标,如评论的情绪或参与的具体时间,就需要对 Youtube 页面进行网络抓取。这种技术通常比较复杂,而且由于平台的内容演绎不断变化,以及其对数据搜刮的严格规定,可能会存在风险。
在下面的模块中,我们将向你展示如何用 Python 构建脚本并高效地从 Youtube 搜刮数据。
要使用 Python 搜刮 Youtube 视频,必须使用代理来规避 IP 禁止和僵尸穿越防范方法。下面是一些代理类型及其说明:
如果有策略地使用这些类型,就有可能在不被发现的情况下从 Youtube 搜刮数据,从而在遵守平台服务条款的同时继续访问数据。此外,正确理解它们还能在您需要找到 代刮.
让我们从如何通过创建脚本来搜刮 Youtube 开始,这里有一些必须安装的软件包。我们首先要安装 Selenium-wire,它是 Selenium 的代理扩展,也有一些关键类和模块。在命令界面中使用以下命令字符串安装这些软件包:
pip install selenium-wire selenium blinker==1.7.0
现在,让我们把目光转向进口。
此时,我们需要加载针对编写脚本的网络元素的库和包。此外,我们还应加入数据处理和运行时管理模块,以确保脚本的高效执行。
from selenium.webdriver.chrome.options import Options
from seleniumwire import webdriver as wiredriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import json
import time
json 模块可帮助将刮擦数据转换为格式正确的 JSON 数据,以便更好地展示,并掩盖我们的 IP 地址。不过,时间模块用于混淆操作,并在检测到过度可预测行为时引入随机性。
此外,它还有助于确保从数据中提取的所需元素已经在页面上。其余的导入都是所需的类或子模块,它们的作用各不相同,稍后将在代码的其他部分进行讨论。
当用 Python 编写的脚本触发 Selenium 实例时,脚本本身会利用我们的 IP 来执行它需要执行的任何任务。这对于像 YouTube 这样从其网站上抓取信息的网站来说,可能会造成很大问题。建议查看网站的 robots 文件,以便更好地了解情况。因此,当您尝试搜刮 YouTube 频道时,您的 IP 可能会受到临时禁止。
为了减轻所有这些挑战,我们需要做几件事。首先,我们必须以三个变量为基础,存储我们将要使用的代理的详细信息。然后,我们定义了一个选项变量 chrome_options,它将被传递给 selenium.Chrome() 实例,以告知刮擦时必须使用哪个代理。代理信息是通过在 chrome_options 中传递所需的参数来设置的。以下是如何使用代理脚本对 Youtube 进行搜刮:
# 指定带有用户名和密码的代理服务器地址
proxy_address = ""
proxy_username = ""
proxy_password = ""
# 使用代理和身份验证设置 Chrome 浏览器选项
chrome_options = Options()
chrome_options.add_argument(f'--proxy-server={proxy_address}')
chrome_options.add_argument(f'--proxy-auth={proxy_username}:{proxy_password}')
# 使用 selenium-wire 创建 WebDriver 实例
driver = wiredriver.Chrome(options=chrome_options)
设置一个名为 "youtube_url_to_scrape "的变量来保存 YouTube 主页的地址。该变量用于 Selenium 的 "driver.get() "方法,这样它就能知道要去哪个特定网页进行刮擦。执行脚本时,该操作将导致打开一个新的 Chrome 浏览器窗口。
youtube_url_to_scrape = ""
# 利用 selenium-wire 的增强功能执行 Selenium 自动化
driver.get(youtube_url_to_scrape)
接下来,我们将介绍 "extract _information() "函数,它可以根据页面名称从页面中提取信息。
我们确保页面上的所有元素都已加载。为此,我们使用 WebDriver API 和 WebDriverWait 暂停脚本,直到示例 "更多 "按钮所代表的元素可用并被点击。当它可用时,Selenium 会执行 JavaScript 点击,查看视频的完整描述。
为了解决这个问题,我们正在实施一个解决方案来消除任何相关问题。我们使用 "动作 "类和 "时间 "模块,每 10 秒向下滚动两次,确保尽可能多地抓取 YouTube 评论。这样就不会出现动态加载内容的问题。
def extract_information() -> dict:
try:
element = WebDriverWait(driver, 15).until(
EC.presence_of_element_located((By.XPATH, '//*[@id="expand"]'))
)
element.click()
time.sleep(10)
actions = ActionChains(driver)
actions.send_keys(Keys.END).perform()
time.sleep(10)
actions.send_keys(Keys.END).perform()
time.sleep(10)
使用 Selenium WebDriver 有多种搜索元素的方法。可以通过 ID、CLASS_NAME 和 XPATH 等方式进行搜索。在本教程(如何用 Python 从 Youtube 搜刮数据)中,我们将把它们结合起来,而不是采用单一的方式。
XPATH 是一种更复杂的变量搜索系统,因为它似乎更注重模式。它确实被认为是最难的,但至少在 Chrome 浏览器上不是这样。
在查看代码时,只需点击并选择复制 XPATH 选项,在 Chrome 浏览器的检查部分右击该选项即可。获取 XPATH 后,就可以使用 "find_elements "方法轻松搜索所有包含视频标题、描述等相关详细信息的组件。
值得一提的是,网页上的某些功能可能有重复的属性,这就是为什么使用基本的 "find_elements() "技术会得到一个列表而不是字符串的原因。在这种情况下,您必须检查列表,并确定哪个索引包含所需信息,哪个文本需要检索。
最后,会返回一个名为 "data "的字典变量,其中包含了刮擦过程中获取的所有信息,因此是后续章节的重要内容。
video_title = driver.find_elements(By.XPATH, '//*[@id="title"]/h1')[0].text
owner = driver.find_elements(By.XPATH, '//*[@id="text"]/a')[0].text
total_number_of_subscribers = \
driver.find_elements(By.XPATH, "//div[@id='upload-info']//yt-formatted-string[@id='owner-sub-count']")[
0].text
video_description = driver.find_elements(By.XPATH, '//*[@id="description-inline-expander"]/yt-attributed-string/span/span')
result = []
for i in video_description:
result.append(i.text)
description = ''.join(result)
publish_date = driver.find_elements(By.XPATH, '//*[@id="info"]/span')[2].text
total_views = driver.find_elements(By.XPATH, '//*[@id="info"]/span')[0].text
number_of_likes = driver.find_elements(By.XPATH, '//*[@id="top-level-buttons-computed"]/segmented-like-dislike-button-view-model/yt-smartimation/div/div/like-button-view-model/toggle-button-view-model/button-view-model/button/div')[
1].text
comment_names = driver.find_elements(By.XPATH, '//*[@id="author-text"]/span')
comment_content = driver.find_elements(By.XPATH, '//*[@id="content-text"]/span')
comment_library = []
for each in range(len(comment_names)):
name = comment_names[each].text
content = comment_content[each].text
indie_comment = {
'name': name,
'comment': content
}
comment_library.append(indie_comment)
data = {
'owner': owner,
'subscribers': total_number_of_subscribers,
'video_title': video_title,
'description': description,
'date': publish_date,
'views': total_views,
'likes': number_of_likes,
'comments': comment_library
}
return data
except Exception as err:
print(f"Error: {err}")
def organize_write_data(data:dict):
output = json.dumps(data, indent=2, ensure_ascii=False).encode("ascii", "ignore").decode("utf-8")
try:
with open("output.json", 'w', encoding='utf-8') as file:
file.write(output)
except Exception as err:
print(f"Error encountered: {err}")
一个名为 "organization_write_data "的用户自定义函数旨在接受前一个操作输出的 "数据"。它的主要工作是在 JSON 格式中构建数据结构,并将其写入名为 output.json 的文件,同时确保在写入文件阶段遵循正确的程序。
现在,我们了解了如何正确搜索 Youtube。到目前为止,这里是我们的搜刮程序的完整代码:
from selenium.webdriver.chrome.options import Options
from seleniumwire import webdriver as wiredriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import json
import time
# 指定带有用户名和密码的代理服务器地址
proxy_address = ""
proxy_username = ""
proxy_password = ""
# 使用代理和身份验证设置 Chrome 浏览器选项
chrome_options = Options()
chrome_options.add_argument(f'--proxy-server={proxy_address}')
chrome_options.add_argument(f'--proxy-auth={proxy_username}:{proxy_password}')
# 使用 selenium-wire 创建 WebDriver 实例
driver = wiredriver.Chrome(options=chrome_options)
youtube_url_to_scrape = ""
# 利用 selenium-wire 的增强功能执行 Selenium 自动化
driver.get(youtube_url_to_scrape)
def extract_information() -> dict:
try:
element = WebDriverWait(driver, 15).until(
EC.presence_of_element_located((By.XPATH, '//*[@id="expand"]'))
)
element.click()
time.sleep(10)
actions = ActionChains(driver)
actions.send_keys(Keys.END).perform()
time.sleep(10)
actions.send_keys(Keys.END).perform()
time.sleep(10)
video_title = driver.find_elements(By.XPATH, '//*[@id="title"]/h1')[0].text
owner = driver.find_elements(By.XPATH, '//*[@id="text"]/a')[0].text
total_number_of_subscribers = \
driver.find_elements(By.XPATH, "//div[@id='upload-info']//yt-formatted-string[@id='owner-sub-count']")[
0].text
video_description = driver.find_elements(By.XPATH,
'//*[@id="description-inline-expander"]/yt-attributed-string/span/span')
result = []
for i in video_description:
result.append(i.text)
description = ''.join(result)
publish_date = driver.find_elements(By.XPATH, '//*[@id="info"]/span')[2].text
total_views = driver.find_elements(By.XPATH, '//*[@id="info"]/span')[0].text
number_of_likes = driver.find_elements(By.XPATH,
'//*[@id="top-level-buttons-computed"]/segmented-like-dislike-button-view-model/yt-smartimation/div/div/like-button-view-model/toggle-button-view-model/button-view-model/button/div')[
1].text
comment_names = driver.find_elements(By.XPATH, '//*[@id="author-text"]/span')
comment_content = driver.find_elements(By.XPATH,
'//*[@id="content-text"]/span')
comment_library = []
for each in range(len(comment_names)):
name = comment_names[each].text
content = comment_content[each].text
indie_comment = {
'name': name,
'comment': content
}
comment_library.append(indie_comment)
data = {
'owner': owner,
'subscribers': total_number_of_subscribers,
'video_title': video_title,
'description': description,
'date': publish_date,
'views': total_views,
'likes': number_of_likes,
'comments': comment_library
}
return data
except Exception as err:
print(f"Error: {err}")
# 将数据记录为 JSON 格式
def organize_write_data(data: dict):
output = json.dumps(data, indent=2, ensure_ascii=False).encode("ascii", "ignore").decode("utf-8")
try:
with open("output.json", 'w', encoding='utf-8') as file:
file.write(output)
except Exception as err:
print(f"Error encountered: {err}")
organize_write_data(extract_information())
driver.quit()
我们现在还知道如何用 Python 搜刮 Youtube 评论。输出结果如下
{
"owner": "Suzie Taylor",
"subscribers": "165K subscribers",
"video_title": "I Spent $185,000 From MrBeast",
"description": "@MrBeast blessed me with $185,000, after SURVIVING 100 DAYS trapped with a STRANGER. Now I want to bless you!\nGive This A Like if you Enjoyed :))\n-\nTo Enter The Giveaway: \nFollow me on Instagram: https://www.instagram.com/sooztaylor/...\nSubscribe to me on Youtube: \n / @suzietaylor \nI am picking winners for the giveaway ONE WEEK from today (December 23rd) \n-\nThank you everyone for all of your love already. This is my dream!",
"date": "Dec 16, 2023",
"views": "4,605,785 ",
"likes": "230K",
"comments": [
{
"name": "",
"comment": "The right person got the money "
},
{
"name": "@Scottster",
"comment": "Way to go Suzie, a worthy winner! Always the thought that counts and you put a lot into it!"
},
{
"name": "@cidsx",
"comment": "I'm so glad that she's paying it forward! She 100% deserved the reward"
},
{
"name": "@Basicskill720",
"comment": "This is amazing Suzie. Way to spread kindness in this dark world. It is much needed !"
},
{
"name": "@eliasnull",
"comment": "You are such a blessing Suzie! The world needs more people like you."
},
{
"name": "@iceline22",
"comment": "That's so awesome you're paying it forward! You seem so genuine, and happy to pass along your good fortune! Amazing! Keep it up!"
},
{
"name": "",
"comment": "Always nice to see a Mr. Beast winner turn around and doing nice things for others. I know this was but a small portion of what you won and nobody expects you to not take care of yourself with that money, but to give back even in small ways can mean so much. Thank you for doing this."
}
]
}
在使用有助于遵守平台规则的自动化或代理脚本时,利用 YouTube 数据库信息的能力非常有价值。上文介绍的 Youtube 搜刮主要方法有助于负责任地采集数据,同时避免被平台禁止或限制。
评论: 0