我正在尝试获取具有XPath的单个节点,但是我在节点上获得了空值,不知道为什么
WebClient wc = new WebClient();
string nodeValue;
string htmlCode = wc.DownloadString("http://www.freeproxylists.net/fr/?c=&pt=&pr=&a%5B%5D=0&a%5B%5D=1&a%5B%5D=2&u=50");
HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.LoadHtml(htmlCode);
HtmlNode node = html.DocumentNode.SelectSingleNode("//table[@class='DataGrid']/tbody/tr[@class='Odd']/td/a");
nodeValue = (node.InnerHtml);
尝试从中获取信息的 html 相比,我在您的 xpath 中看到至少 2 个错误。
- 没有具有
作为祖先。 - 即使你的Xpath工作了,那么你也只能得到一个
看起来他们正在对您要做的事情进行某种懒惰的保护。由于 a 标签只是用 IPDecode 中括起来的十六进制表示。所以提取链接真的没有问题。但你至少可以做的是在发布之前查看html。你显然根本没有尝试过。由于您从当前代码中获取的html不是您提供给我们的链接的<正文> - 这意味着您必须从绝对URL获取html页面或仅使用Selenium。正文>
但是由于我是一个膨胀的人,我将使用Xpath,Html Agility Pack和Selenium为您制作整个解决方案。以下解决方案获取网站的 html。然后仅读取具有 class="Odd" 的
private void HtmlParser(string url)
{
HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.OptionFixNestedTags=true;
GetHTML(url);
htmlDoc.Load("x.html", Encoding.ASCII, true);
HtmlNodeCollection nodes = htmlDoc.DocumentNode.SelectNodes("//table[@class='DataGrid']/descendant::*/tr[@class='Odd']/td/script");
List<string> urls = new List<string>();
foreach(HtmlNode x in nodes)
{
urls.Add(ConvertStringToUrl(x.InnerText));
}
Console.WriteLine(ReadingTheAnchor(urls[0]));
}
private string ConvertStringToUrl(string octUrl)
{
octUrl = octUrl.Replace("IPDecode("", "");
octUrl = octUrl.Remove(octUrl.Length -2);
octUrl = octUrl.Replace("%", "");
string ascii = string.Empty;
for (int i = 0; i < octUrl.Length; i += 2)
{
String hs = string.Empty;
hs = octUrl.Substring(i,2);
uint decval = System.Convert.ToUInt32(hs, 16);
char character = System.Convert.ToChar(decval);
ascii += character;
}
//Now you get the <a> containing the links. which all can be read as seperate html files containing just a <a>
Console.WriteLine(ascii);
return ascii;
}
private string ReadingTheAnchor(string anchor)
{
//returns url of anchor
HtmlDocument anchorHtml = new HtmlAgilityPack.HtmlDocument();
anchorHtml.LoadHtml(anchor);
HtmlNode h = anchorHtml.DocumentNode.SelectSingleNode("a");
return h.GetAttributeValue("href", "");
}
//using OpenQA.Selenium; using OpenQA.Selenium.Firefox;
private void GetHTML(string url)
{
using (var driver = new FirefoxDriver())
{
driver.Navigate().GoToUrl(url);
Console.Clear();
System.IO.File.WriteAllText("x.html", driver.PageSource);
}
}