Python 爬取 Niconico 视频教程:获取标题和观看次数
当然可以帮你写一个爬取 Niconico 视频的代码。以下是一个示例代码,它使用 Python 的 requests 和 BeautifulSoup 库来进行网页内容的获取和解析:
import requests
from bs4 import BeautifulSoup
def get_niconico_videos(keyword):
url = f'https://www.nicovideo.jp/search/{keyword}?sort=f&order=d'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
videos = soup.find_all('li', class_='item')
for video in videos:
title = video.find('h2').text
views = video.find(class_='count').text
print(f'Title: {title}')
print(f'Views: {views}
')
# 使用示例
get_niconico_videos('python')
以上代码中,get_niconico_videos 函数接收一个参数 keyword,用于指定搜索关键词。代码会发送 GET 请求到 niconico 的搜索页面,然后使用 BeautifulSoup 解析返回的 HTML 内容,提取视频的标题和观看次数,并输出到控制台。
请注意,为了模拟浏览器请求,我们在代码中添加了一个 User-Agent 头部,以避免被网站屏蔽。你可以根据需要修改 User-Agent 的值。
当然,你也可以根据自己的需求对代码进行扩展,例如获取视频的链接、上传者信息等。
原文地址: https://www.cveoy.top/t/topic/Cuu 著作权归作者所有。请勿转载和采集!