這裏新增了C#並運行異步任務。使用C從網頁中刮取JSON#
我試圖從網站上刮一些音樂專輯信息。網頁的搜索以明文生成JSON對象,但我似乎無法訪問任何DOM信息。以下是我嘗試過的(使用HtmlAgilityPack):
using HtmlAgilityPack;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
public async Task<String> AlbumScraper(string albumname) {
HtmlWeb web = new HtmlWeb();
string albumurl = Uri.EscapeUriString("https://www.metal-archives.com/search/ajax-album-search/?field=title&query=" + albumname);
Console.Write(albumurl);
var albumdoc = await Task.Factory.StartNew(() => web.Load(albumurl));
string albumjson = "";
if (albumdoc.DocumentNode != null) {
albumjson = albumdoc.DocumentNode.InnerText;
}
return albumjson;
}
private async void Form1_Load(object sender, EventArgs e) {
string rawtext = await AlbumScraper("rust+in+peace");
Console.Write(rawtext);
}
}
}
如何獲取生成的JSON文本?我可以清楚地看到它時,我加載「albumurl」網址...
爲什麼不能用一個簡單的HTTP GET請求獲取JSON數據然後將其解析爲一個對象? –
爲什麼你想要加載爲HTML/XML?它返回JSON而不是網頁,因此沒有DOM信息。只需使用JSON.NET解析器來解析響應,如JSON.NET –