2016-08-23 5 views
0

私はWebCrawlerで作業しています。このWebクローラーは、指定された検索ワードに応じてGoogle検索からすべてのリンクを取得します。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上の任意のヘルプを見つけることができませんでした。

答えて

0

xpathには]が追加されているようです。

この:

//a[@href] | //*[not(self::g-img)]] 

は次のようになります。

//a[@href] | //*[not(self::g-img)] 

それが今で文法的に正しいですが、私はそれはあなたが望むものを選択することになるとは思いません。 href属性を持つすべてのa要素と、g-imgという名前のないすべての要素の和集合を選択します。

代わりにこれを試してみてください:

//*[@href and not(self::g-img)] 
関連する問題