【发布时间】:2017-06-17 13:04:31
【问题描述】:
我正在尝试获取课程的innerText。
这是我的代码:
using (HttpClient clientduplicate = new HttpClient())
{
clientduplicate.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident / 6.0)");
using (HttpResponseMessage responseduplicate = await clientduplicate.GetAsync(@"https://www.investing.com/news/stock-market-news/warren-buffett:-i-bought-$12-billion-of-stock-after-trump-won-456954")
using (HttpContent contentduplicate = responseduplicate.Content)
{
try
{
string resultduplicate = await contentduplicate.ReadAsStringAsync();
var websiteduplicate = new HtmlDocument();
websiteduplicate.LoadHtml(resultduplicate);
var titlesduplicate = websiteduplicate.DocumentNode.Descendants("div").FirstOrDefault(o => o.GetAttributeValue("class", "") == "arial_14 clear WYSIWYG newsPage");
var match = Regex.Match(titlesduplicate.InnerText, @"(.*?)<!--", RegexOptions.Singleline).Groups[1].Value;
Debug.WriteLine(match.TrimStart());
}
catch(Exception ex1)
{
var dialog2 = new MessageDialog(ex1.Message);
await dialog2.ShowAsync();
}
}
}
现在的问题是这也会返回我图片上的文字。我可以找到解决方法,但我想知道是否有其他方法。 更简单/更快的东西。
另外,当我在其他文章/网址上使用它时,还有其他小错误。
【问题讨论】:
-
您可以使用类似
titlesduplicate.SelectNodes("./img")?.ToList().ForEach(i => i.Remove());的 xpath 查询来清理您的节点,对于选择重复标题,请使用var titlesduplicate = websiteduplicate.DocumentNode.SelectSingleNode("//div[contains(@class, 'newsPage')]"); -
你能详细说明错误是什么吗?
-
@GantTheWanderer 字母编码,字母更改为 html。小事。
-
我会接受洪曹的回答,删除令人反感的材料。否则,您的选择器需要更加准确。你想收集什么信息,你打算用它做什么?
-
如果我是 Web 服务器,我不会发送换行符,因为它们在 HTML 和许多其他类型的标记中不是必需的。换行符使人类更容易阅读,但它只是浪费了计算机解析的空间,多余的数据通过管道不必要地传输。
标签: c# class http html-agility-pack innertext