.NET 4.x Ошибка в парсере html на второй итерации - C#

Узнай цену своей работы

Формулировка задачи:

Добрый день! Пытаюсь сделать парсер. Для начала делаю два POST запроса, далее GET запрос. После второго POST запроса я вібирают href с нужного div-a. Но при формировании из href нового адресса для GET запроса вілазит ошибка. Помогите пожалуйста.
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Threading.Tasks;
  13. using System.Web;
  14. using System.Web.UI;
  15. using System.Windows.Forms;
  16. using HtmlAgilityPack;
  17.  
  18. namespace WindowsFormsApplicationParce
  19. {
  20. public partial class Form1 : Form
  21. {
  22. UriBuilder uriBuilder = new UriBuilder();
  23. public Form1()
  24. {
  25. InitializeComponent();
  26. }
  27. private void button1_Click(object sender, EventArgs e)
  28. {
  29. // Create a request using a URL that can receive a post.
  30. WebRequest request = WebRequest.Create("http://www.kangaroo.com.ua/index.php?r=conreq/results_int");
  31. // Set the Method property of the request to POST.
  32. request.Method = "POST";
  33. // Create POST data and convert it to a byte array.
  34. string postData = "action=getSchoolsByRegion&region=10";
  35. byte[] byteArray = Encoding.UTF8.GetBytes(postData);
  36. // Set the ContentType property of the WebRequest.
  37. request.ContentType = "application/x-www-form-urlencoded";
  38. // Set the ContentLength property of the WebRequest.
  39. request.ContentLength = byteArray.Length;
  40. // Get the request stream.
  41. Stream dataStream = request.GetRequestStream();
  42. // Write the data to the request stream.
  43. dataStream.Write(byteArray, 0, byteArray.Length);
  44. // Close the Stream object.
  45. dataStream.Close();
  46. // Get the response.
  47. WebResponse response = request.GetResponse();
  48. // Display the status.
  49. Console.WriteLine(((HttpWebResponse) response).StatusDescription);
  50. // Get the stream containing content returned by the server.
  51. dataStream = response.GetResponseStream();
  52. // Open the stream using a StreamReader for easy access.
  53. StreamReader reader = new StreamReader(dataStream);
  54. // Read the content.
  55. string responseFromServer = reader.ReadToEnd();
  56. // Display the content.
  57.  
  58. // Create a request using a URL that can receive a post.
  59. request = WebRequest.Create("http://www.kangaroo.com.ua/index.php?r=conreq/resstudents");
  60. // Set the Method property of the request to POST.
  61. request.Method = "POST";
  62. // Create POST data and convert it to a byte array.
  63. postData = "schoolId=10245";
  64. byteArray = Encoding.UTF8.GetBytes(postData);
  65. // Set the ContentType property of the WebRequest.
  66. request.ContentType = "application/x-www-form-urlencoded";
  67. // Set the ContentLength property of the WebRequest.
  68. request.ContentLength = byteArray.Length;
  69. // Get the request stream.
  70. dataStream = request.GetRequestStream();
  71. // Write the data to the request stream.
  72. dataStream.Write(byteArray, 0, byteArray.Length);
  73. // Close the Stream object.
  74. dataStream.Close();
  75. // Get the response.
  76. response = request.GetResponse();
  77. // Display the status.
  78. Console.WriteLine(((HttpWebResponse) response).StatusDescription);
  79. // Get the stream containing content returned by the server.
  80. dataStream = response.GetResponseStream();
  81. // Open the stream using a StreamReader for easy access.
  82. reader = new StreamReader(dataStream);
  83. // Read the content.
  84. responseFromServer = reader.ReadToEnd();
  85. // Display the content.
  86. textBox1.Text = responseFromServer.ToString();
  87. HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
  88. string htmlString = responseFromServer;
  89. document.LoadHtml(responseFromServer);
  90. var list = document.DocumentNode.SelectNodes("//div[@id='content']/a[@href]");
  91. foreach (var obj in list)
  92. {
  93. var url = obj.SelectSingleNode(".").Attributes["href"].Value;
  94. //url = HttpUtility.HtmlDecode(url);
  95. //url = HttpUtility.UrlEncode(url);
  96. textBox1.Text += url + Environment.NewLine;
  97. Uri urii = new Uri(@"http:\\kangaroo.com.ua"+ url);
  98. string r = HttpUtility.ParseQueryString(urii.Query).Get("r");
  99. string student = HttpUtility.ParseQueryString(urii.Query).Get("student");
  100. string schoolId = HttpUtility.ParseQueryString(urii.Query).Get("schoolId");
  101. string student_name = HttpUtility.ParseQueryString(urii.Query).Get("student_name");
  102. uriBuilder.Scheme = "http";
  103. uriBuilder.Host = "www.kangaroo.com.ua";
  104. uriBuilder.Path = "index.php";
  105. var query = HttpUtility.ParseQueryString(uriBuilder.Query);
  106. query["r"] = r;
  107. query["student"] = student;
  108. query["schoolId"] = schoolId;
  109. query["student_name"] = student_name;
  110. uriBuilder.Query = query.ToString();
  111. request =
  112. (HttpWebRequest)
  113. WebRequest.Create(uriBuilder.Uri)as HttpWebRequest;
  114. request.Method = "GET";
  115. response = (HttpWebResponse)request.GetResponse();
  116. dataStream = response.GetResponseStream();
  117. reader = new StreamReader(dataStream);
  118. // Read the content.
  119. responseFromServer = reader.ReadToEnd();
  120. htmlString = responseFromServer;
  121. document.LoadHtml(htmlString);
  122. HtmlNode bodyNode = document.DocumentNode.SelectSingleNode("//div[@id='content']");
  123. if (String.IsNullOrEmpty(bodyNode.ToString()))
  124. {
  125. bodyNode = bodyNode.SelectSingleNode("//input[@id='surname']");
  126. textBox1.Text += bodyNode.Attributes["value"].Value;
  127. bodyNode = bodyNode.SelectSingleNode("//input[@id='name']");
  128. textBox1.Text += bodyNode.Attributes["value"].Value;
  129. bodyNode = bodyNode.SelectSingleNode("//input[@id='patronymic']");
  130. textBox1.Text += bodyNode.Attributes["value"].Value;
  131. //количество балов
  132. bodyNode = document.DocumentNode.SelectSingleNode("//div[@class='legend_total']");
  133. textBox1.Text += bodyNode.SelectSingleNode("//b").InnerText;
  134. }
  135. }
  136. }
  137. }

Решение задачи: «.NET 4.x Ошибка в парсере html на второй итерации»

textual
Листинг программы
  1. var list = document.DocumentNode.SelectNodes("//div[@id='content']/a[@href]").Select(node => node.Attributes["href"].Value).ToArray();
  2. foreach (string url in list)
  3. {
  4.     textBox1Text += url + Environment.NewLine;
  5.     Uri urii = new Uri(@"http:\\kangaroo.com.ua"+ url);

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

10   голосов , оценка 4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут