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上找到任何幫助。