在获得一些代码帮助之后,我使用HttpClient
提取了数据。
我是新来编写代码的人,所以找不到我的问题。有人可以帮我解决这个问题。
我希望将要剪贴的表的数据写入控制台行。
感谢任何帮助
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using HtmlAgilityPack;
namespace weatherCheck
{
class Program
{
private static void Main(string[] args)
{
GetHtmlAsync();
Console.ReadLine();
}
protected static async void GetHtmlAsync()
{
var url = "https://www.weatherzone.com.au/vic/melbourne/melbourne";
var httpClient = new HttpClient();
var html = await httpClient.GetStringAsync(url);
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
//grab the rain chance, rain in mm and date
var MyTable = Enumerable.FirstOrDefault(htmlDocument.DocumentNode.Descendants("table")
.Where(table => table.Attributes.Contains("id"))
, table => table.Attributes["id"].Value == "forecast-table");
List<HtmlNode> rows = htmlDocument.DocumentNode.SelectNodes("//tr").ToList();
foreach (var row in rows)
{
try
{
if (MyTable != null)
{
Console.WriteLine(MyTable.GetAttributeValue("forecast-table", " "));
}
}
catch (Exception)
{
}
}
}
}
}
答案 0 :(得分:0)
从Doc,对于GetAttributeValue(name,def)
,如果找不到该属性,它将返回def。
因此,它将打印“”(如果您的情况下找不到该属性,则为空字符串)
删除async
和await
,因为您已经呼叫httpClient.GetStringAsync(url);
var html =httpClient.GetStringAsync(url).Result;
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
然后打印
Console.WriteLine(MyTable.GetAttributeValue("forecast-table","SOME_TEXT_HERE").ToString());
答案 1 :(得分:0)
我用您的代码查找了值,但是它对我也没有产生任何作用。当我查看forecast-table
以查看它正在抓取的整个HTML时,我在文档中没有看到任何反映属性row != null
的东西。
此外,您每次循环遍历行时都在验证MyTable。您应该验证row
以及来自var MyTable = Enumerable.FirstOrDefault(htmlDocument.DocumentNode.Descendants("table")
.Where(table => table.Attributes.Contains("id")), table => table.Attributes["id"].Value == "forecast-table");
List<HtmlNode> rows = htmlDocument.DocumentNode.SelectNodes("//tr").ToList();
foreach (var row in rows)
{
try
{
if (row != null) // Here, it should be row, not My Table along with MyTable in line below.
Console.WriteLine(row.GetAttributeValue("forecast-table", " "));
}
catch (Exception)
{
}
}
的打印属性。
OpenFX 11
问题是
您还应该知道,在chrome上使用开发工具查看的HTML与在HtmlAgilityPack中看到的HTML不同。 Chrome在执行脚本后呈现页面,其中HtmlAgilityPack只是为您提供页面的默认HTML。这就是为什么您无法获得预报表的价值的原因。