0
我正在使用WebCrawler。这个网络抓取工具根据给定的搜索词获得谷歌搜索的所有链接。XPath选择链接但不是图片
我的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或google上找到任何帮助。