【发布时间】:2016-08-23 07:13:41
【问题描述】:
我正在开发一个 WebCrawler。这个网络爬虫会根据给定的搜索词从 Google 搜索中获取所有链接。
我的 WebCrawler 成功列出了所有链接。 问题出在:我不希望 WebCrawler 列出 Google 图片的链接。
我使用 XPath 选择节点。 这是我用于链接选择的 XPath:
//a[@href]
-- 这很好用。
这是我选择的链接而不是图片:
/a[@href] | //*[not(self::g-img)]]
-- 这不起作用。
Google 使用<g-img...>...</g-img> 标记图片。
我收到以下XPath Exception 错误:
An unhandled exception of type 'System.Xml.XPath.XPathException' occurred in System.Xml.dll
Additional information: '//a[@href] | //*[not(self::g-img)]]' is an invalid Token.
这是我点击按钮的 C# 代码:
private void urlButton_Click(object sender, EventArgs e)
{
itemsListBox.Items.Clear();
StringBuilder sb = new StringBuilder();
byte[] resultsBuffer = new byte[8192];
string searchResults = "http://google.com/search?q=" + keyWordTextBox.Text.Trim() + "&num=" + numTextBox.Text;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(searchResults);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream rStream = webResponse.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = rStream.Read(resultsBuffer, 0, resultsBuffer.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(resultsBuffer, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string sbString = sb.ToString();
HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.OptionOutputAsXml = true;
html.LoadHtml(sbString);
HtmlNode doc = html.DocumentNode;
string nodeSelection = "//a[@href] | //*[not(self::g-img)]]";
// TODO insert correct xpath
foreach (HtmlNode link in doc.SelectNodes(nodeSelection))
{
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (!hrefValue.ToString().ToUpper().Contains("GOOGLE") && hrefValue.ToString().Contains("/url?q=") && (hrefValue.ToString().ToUpper().Contains("HTTP://") || hrefValue.ToString().ToUpper().Contains("HTTPS://")))
{
int index = hrefValue.IndexOf("&");
if (index > 0)
{
hrefValue = hrefValue.Substring(0, index);
itemsListBox.Items.Add(hrefValue.Replace("/url?q=", ""));
}
}
}
}
我使用HtmlAgilityPack。在这种情况下非常有用。我尝试解决这个问题已经有一段时间了,但我无法在 stackoverflow 或谷歌上找到任何帮助。
【问题讨论】:
标签: c# html xml xpath web-crawler