I use this code for get html source of url with HtmlAgilityPack:
private string GetUrlSource(string urlAddress)
{
string content = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
content = readStream.ReadToEnd();
response.Close();
readStream.Close();
}
return content;
}
then, use this code for get data:
var source = GetUrlSource(urlAddress);
var htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(source);
var nodes = htmlDoc.DocumentNode.SelectNodes("//div[@class='linear-view']/table/tr/td");
and my result for nodes are :
<tr>
<th>Title</th>
<th>Publisher</th>
</tr>
<tr>
<td><a href="http://link1.com" id="14.4">Title1</a></td>
<td>Publisher1</td>
</tr>
<tr>
<td><a href="http://link2.com" id="12.0">Title2</a></td>
<td>Publisher2</td>
</tr>
<tr>
<td><a href="http://link3.com/" id="84.4">Title3</a></td>
<td>Publisher3</td>
</tr>
I use this code for get data:
foreach (var node in nodes)
{
HtmlNodeCollection rows = node.SelectNodes(".//a");
if (rows != null)
{
for (int j = 0; j < rows.Count; ++j)
{
var link = rows[j].Attributes["href"].Value;
var title = rows[j].InnerText;
}
}
else
{
var publisher = node.InnerText;
}
}
How can I get link, title & publisher of every tr tag without if & else?
for example : http://link1.com , Title1 , Publisher1
and http://link2.com , Title2 , Publisher2
and http://link3.com , Title3 , Publisher3