对于一个非商业性的私立学校项目,我正在创建一个软件,根据Spotify当前播放的歌曲搜索歌词.我必须在C#(要求)中这样做,但如果我愿意,我可以使用其他语言.
我发现了一些可以用来获取歌词的网站.我已经成功获取了整个HTML代码,但之后我不知道该怎么做.我问过我的老师,她告诉我使用XML(我也发现很复杂:p),所以我已经阅读了很多关于它并搜索了一些例子,但是没有发现任何看起来适用于我的情况.
假设我想从musixmatch.com获取歌词:
(人类可读的改动)HTML:
<span data-reactid="199">
<p class="mxm-lyrics__content" data-reactid="200">First line of the lyrics!
These words will never be ignored
I don't want a battle
</p>
<!-- react-empty: 201 -->
<div data-reactid="202">
<div class="inline_video_ad_container_container" data-reactid="203">
<div id="inline_video_ad_container" data-reactid="204">
<div class="" style="line-height:0;" data-reactid="205">
<div id="div_gpt_ad_outofpage_musixmatch_desktop_lyrics" data-reactid="206">
<script type="text/javascript">
//Really nice google ad JS which I have removed;
</script>
</div>
</div>
</div>
</div>
<p class="mxm-lyrics__content" data-reactid="207">But I got a war
More fancy lyrics
And lines
That I want to fetch
And display
Tralala
lala
Trouble!
</p>
</div>
</span>
Run Code Online (Sandbox Code Playgroud)
请注意,歌词的前三行位于顶部,其余部分位于底部<p>.另请注意,这两个<p>标签具有相同的类.完整的html源代码可以在这里找到:
view-source:https://www.musixmatch.com/lyrics/Bullet-for-My-Valentine/You-Want-a-Battle-Here%E2%80%99s-a-War在97行左右,代码片段开始.
所以在这个具体的例子中有歌词,并且有很多我不需要的代码.到目前为止,我已经尝试使用以下C#获取html代码:
string source = "https://www.musixmatch.com/lyrics/Bullet-for-My-Valentine/You-Want-a-Battle-Here’s-a-War";
// The HtmlWeb class is a utility class to get the HTML over HTTP
HtmlWeb htmlWeb = new HtmlWeb();
// Creates an HtmlDocument object from an URL
HtmlAgilityPack.HtmlDocument document = htmlWeb.Load(source);
// Targets a specific node
HtmlNode someNode = document.GetElementbyId("mxm - lyrics__content");
if (someNode != null)
{
Console.WriteLine(someNode);
} else
{
Console.WriteLine("Nope");
}
foreach (var node in document.DocumentNode.SelectNodes("//span/div[@id='site']/p[@class='mxm-lyrics__content']"))
{
// here is your text: node.InnerText "//div[@class='sideInfoPlayer']/span[@class='wrap']"
Console.WriteLine(node.InnerText);
}
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)
整个html的获取工作,但提取没有.我坚持从html中提取歌词.因为对于这个页面,歌词不在ID标签中,所以我不能只使用GetElementbyId.有人能指出我正确的方向吗?我想支持多个站点,所以我必须为不同的站点做几次.
解决方案之一
var htmlWeb = new HtmlWeb();
var documentNode = htmlWeb.Load(source).DocumentNode;
var findclasses = documentNode.Descendants("p")
.Where(d => d.Attributes["class"]?.Value.Contains("mxm-lyrics__content") == true);
//or
var findclasses = documentNode.SelectNodes("//p[contains(@class,'mxm-lyrics__content')]")
var text = string.Join(Environment.NewLine, findclasses.Select(x => x.InnerText));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2351 次 |
| 最近记录: |