2311061106/frontend/tests/find-free-song-urls.test.js
23175 b8b09fd9d4
Some checks failed
autograde-final-vibevault / check-trigger (push) Successful in 13s
autograde-final-vibevault / grade (push) Failing after 55s
完成作业
2025-12-14 16:02:40 +08:00

107 lines
3.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { test } from '@playwright/test';
test('寻找免费的不重复歌曲URL', async ({ page }) => {
// 用于存储找到的唯一歌曲URL
const uniqueSongUrls = new Set();
// 要访问的免费音乐网站列表
const freeMusicSites = [
{
name: 'SoundHelix',
url: 'https://www.soundhelix.com/examples/mp3',
selector: 'a[href$=".mp3"]'
},
{
name: 'Free Music Archive',
url: 'https://freemusicarchive.org/genre/ambient',
selector: 'a.play-item'
}
];
console.log('开始寻找免费歌曲URL...');
// 遍历每个免费音乐网站
for (const site of freeMusicSites) {
try {
console.log(`\n正在访问: ${site.name}`);
await page.goto(site.url, { timeout: 30000 });
await page.waitForLoadState('networkidle');
// 提取MP3链接
const links = page.locator(site.selector);
const count = await links.count();
console.log(`${site.name} 找到 ${count} 个链接`);
// 遍历所有找到的链接
for (let i = 0; i < count && uniqueSongUrls.size < 10; i++) {
let href = await links.nth(i).getAttribute('href');
// 处理相对链接
if (href && !href.startsWith('http')) {
// 确保链接以.mp3结尾
if (href.endsWith('.mp3')) {
// 创建完整的URL
const url = new URL(href, site.url);
href = url.href;
} else {
// 如果不是MP3链接尝试从页面中提取MP3
try {
// 点击链接进入详情页
await links.nth(i).click();
await page.waitForLoadState('networkidle');
// 在详情页寻找MP3链接
const mp3Links = page.locator('a[href$=".mp3"]');
if (await mp3Links.count() > 0) {
href = await mp3Links.first().getAttribute('href');
if (href && !href.startsWith('http')) {
const url = new URL(href, page.url());
href = url.href;
}
}
// 返回上一页
await page.goBack();
await page.waitForLoadState('networkidle');
} catch (e) {
console.error(`处理 ${site.name} 的链接 ${i} 时出错: ${e.message}`);
// 如果出错,继续下一个链接
continue;
}
}
}
// 如果是有效的MP3链接添加到集合中
if (href && href.endsWith('.mp3')) {
uniqueSongUrls.add(href);
console.log(`✓ 找到歌曲URL: ${href}`);
}
}
} catch (e) {
console.error(`访问 ${site.name} 时出错: ${e.message}`);
continue;
}
}
// 输出结果
console.log('\n=========================');
console.log('找到的免费歌曲URL列表:');
console.log('=========================');
const urlsArray = Array.from(uniqueSongUrls);
urlsArray.forEach((url, index) => {
console.log(`${index + 1}. ${url}`);
});
console.log('\n=========================');
console.log(`总共找到 ${urlsArray.length} 个不重复的免费歌曲URL`);
console.log('=========================');
// 确保至少找到一些URL
if (urlsArray.length === 0) {
console.error('没有找到任何免费歌曲URL');
throw new Error('没有找到任何免费歌曲URL');
}
});