I am trying to create a news agent to get the news from the websites.so i have to use a html parser
like HtmlAgilityPack
.so here you ca see my code :
public async void parsing(string website)
{
HttpClient http = new HttpClient();
var response = await http.GetByteArrayAsync(website);
String source = Encoding.GetEncoding("utf-8").GetString(response, 0, response.Length - 1);
source = WebUtility.HtmlDecode(source);
HtmlDocument resultat = new HtmlDocument();
resultat.LoadHtml(source);
List<HtmlNode> toftitle = resultat.DocumentNode.Descendants().Where
(x => (x.Name == "div" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("latest-news"))).ToList();
var li = toftitle[0].Descendants("li").ToList();
foreach (var item in li)
{
var link = item.Descendants("a").ToList()[0].GetAttributeValue("href", null);
var img = item.Descendants("img").ToList()[0].GetAttributeValue("src", null);
}
}
here is my html code that should be parsed :
<a href="/news?p_p_id=56_INSTANCE_tVzMoLp4zfGh&_56_INSTANCE_tVzMoLp4zfGh_mode=news&_56_INSTANCE_tVzMoLp4zfGh_newsId=3153832&p_p_state=maximized">› پانل «بررسي سازوکارهاي تأمين منابع مالي براي توسعۀ Ùناوري» به‌عنوان پانل برتر پنجمين Ú©Ù†ÙØ±Ø§Ù†Ø³ بين‌المللي Ùˆ نهمين Ú©Ù†ÙØ±Ø§Ù†Ø³ ملي مديريت Ùناوري معرÙÙŠ شد</a>
<a href="/news?p_p_id=56_INSTANCE_tVzMoLp4zfGh&_56_INSTANCE_tVzMoLp4zfGh_mode=news&_56_INSTANCE_tVzMoLp4zfGh_newsId=3135970&p_p_state=maximized">› ÙØ±Ø¢ÛŒÙ†Ø¯ Ùˆ ÙØ±Ù… درخواست Ø§Ø³ØªÙØ§Ø¯Ù‡ از تسهیلات ØÙ…ایتی بلاعوض صندوق نوآوری Ùˆ Ø´Ú©ÙˆÙØ§ÛŒÛŒ جهت ØØ¶ÙˆØ± شرکت های دانش بنیان در جایزه ملی مدیریت Ùناوری Ùˆ نوآوری</a>
So the problem is i can get the href link
but not href value
.I mean i can get the news url but not title پانل «بررسي سازوکارهاي تأمين منابع مالي براي توسعۀ Ùناوري» به‌عنوان پانل برتر پنجمين Ú©Ù†ÙØ±Ø§Ù†Ø³ بين‌المللي Ùˆ نهمين Ú©Ù†ÙØ±Ø§Ù†Ø³ ملي مديريت Ùناوري معرÙÙŠ شد
.
How can i get that ?
I just should use this code to get the innertext of href :
string tistle = item.Descendants("a").ToList()[0].InnerText;
you can use like this :
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(result);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("a"))
{
string value = link.InnerText; // here you can get href value
}