从网页中提取数据,解析特定部分并显示它

我已经使用这个网站很长时间来找到我的问题的答案,但我无法找到这个问题的答案。

我正在与一个class级项目的小组合作。 我们要建立一个小型的“游戏交易”网站,允许人们注册,投入他们想要交易的游戏,接受他人交易或要求交易。

我们的网站function提前很长时间,因此我们尝试向网站添加更多内容。 我想做的一件事就是把投入的游戏与Metacritic联系起来。

这就是我需要做的。 我需要(在visual studio 2012中使用asp和c#)获得metacritic的正确游戏页面,拉取其数据,解析特定部分,然后在我们的页面上显示数据。

基本上当你选择想要交易的游戏时,我们想要一个小的div来显示游戏的信息和评级。 我想这样做是为了了解更多信息并从这个项目中获得一些我不必从头开始的东西。

我想知道是否有人能告诉我从哪里开始。 我不知道如何从页面中提取数据。 我仍然想弄清楚我是否需​​要尝试写一些东西来自动搜索游戏的标题并找到那样的页面,或者我是否能找到某种方式直接进入游戏页面。 一旦我获得了数据,我就不知道如何从中获取我需要的具体信息。

其中一个不容易做到的事情就是我正在学习c ++以及c#和asp,所以我不断将电线交叉。 如果有人能指出我正确的方向,那将是一个很大的帮助。 谢谢

这个小例子使用HtmlAgilityPack ,并使用XPath选择器来获取所需的元素。

 protected void Page_Load(object sender, EventArgs e) { string Url = "http://www.metacritic.com/game/pc/halo-spartan-assault"; HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load(Url); string metascore = doc.DocumentNode.SelectNodes("//*[@id=\"main\"]/div[3]/div/div[2]/div[1]/div[1]/div/div/div[2]/a/span[1]")[0].InnerText; string userscore = doc.DocumentNode.SelectNodes("//*[@id=\"main\"]/div[3]/div/div[2]/div[1]/div[2]/div[1]/div/div[2]/a/span[1]")[0].InnerText; string summary = doc.DocumentNode.SelectNodes("//*[@id=\"main\"]/div[3]/div/div[2]/div[2]/div[1]/ul/li/span[2]/span/span[1]")[0].InnerText; } 

获取给定元素的XPath的简单方法是使用您的Web浏览器(我使用Chrome)开发人员工具:

  • 打开开发人员工具(Windows上的F12Ctrl + Shift + C或Mac的Command + Shift + C )。
  • 在页面中选择您想要XPath的元素。
  • 右键单击“元素”选项卡中的元素。
  • 单击“Copy as XPath”。

你可以像在c#中那样粘贴它(如我的代码所示),但请确保转义引号。

您必须确保使用某些error handling技术,因为如果Web Scrapping更改了页面的HTML格式,则可能会导致错误。

我推荐Dcsoup 。 它有一个nuget包 ,它使用css选择器,所以如果你使用jquery就很熟悉。 我尝试过其他人,但它是我发现的最好和最容易使用的。 没有太多的文档,但它是开放源代码和java jsoup库的一个端口,具有良好的文档 。 我非常喜欢它。

 var doc = Dcsoup.Parse(new Uri("http://www.metacritic.com/game/pc/fallout-4"), 5000); // 86 var ratingSpan = doc.Select("span[itemprop=ratingValue]"); int ratingValue = int.Parse(ratingSpan.Text); // selectors match both critic and user scores var scoreDiv = doc.Select("div.score_summary"); var scoreAnchor = scoreDiv.Select("a.metascore_anchor"); int criticRating = int.Parse(scoreAnchor[0].Text); float userRating = float.Parse(scoreAnchor[1].Text); 

我看了,Metacritic.com没有API。

您可以使用HttpWebRequest将网站内容作为字符串获取。

 using System.Net; using System.IO; using System.Windows.Forms; string result = null; string url = "http://www.stackoverflow.com"; WebResponse response = null; StreamReader reader = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; response = request.GetResponse(); reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd(); } catch (Exception ex) { // handle error MessageBox.Show(ex.Message); } finally { if (reader != null) reader.Close(); if (response != null) response.Close(); } 

然后,您可以通过利用Metacritic使用元标记来解析所需数据的字符串。 以下是元标记中提供的信息:

  • OG:标题
  • OG:类型
  • OG:url
  • OG:图像
  • OG:SITE_NAME
  • OG:描述

每个标签的格式为: meta name="og:title" content="In a World..."