这里是 C# 和运行异步任务的新手。
我正在尝试从网站上抓取一些音乐专辑信息。该网页的搜索以明文形式生成一个 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”URL 时,我可以清楚地看到它...
最佳答案
可以通过在线工具生成http://json2csharp.com/ 然后将生成的类添加到您的代码中
public class AlbumSearchResponse
{
public string error { get; set; }
public int iTotalRecords { get; set; }
public int iTotalDisplayRecords { get; set; }
public int sEcho { get; set; }
public List<List<string>> aaData { get; set; }
}
将您的响应文本转换为类
var data = JsonConvert.DeserializeObject<AlbumSearchResponse>(response);
foreach (var item in data.aaData)
{
//do whatever your want with data
}
你还需要从 nuget 添加 newtonsoft json 包来让 JsonConvert 工作
关于c# - 使用 C# 从网页中抓取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44897486/