using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
public class GoogleParser
{
public const string Query = "http://www.google.ru/ie?q={0}&num={1}&start={2}";
private WebResponse response;
private string pageSource;
private int linksCount;
///
/// Колличество ссылок указываемых при запросе к гуглу
///
public int LinksCount
{
get
{
return linksCount;
}
set
{
linksCount = value > 100 ? 100 : value;
}
}
public int StartFrom { get; set; }
///
/// Игнорить ссылки ведущие на гугл
///
[DefaultValue(true)]
public bool IgnoreGoogleLinks { get; set; }
///
/// Сформированный запрос к гуглу
///
public string SearchQuery { get; private set; }
public WebProxy Proxy { get; set; }
private string searchKeyword;
///
/// Поисковой запрос
///
public string SearchKeyword
{
get
{
return searchKeyword;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new Exception("Keyword cannot be empty or null");
}
searchKeyword = value;
}
}
private string userAgent;
///
/// UserAgent используемый при запросе
///
public string UserAgent
{
get
{
return userAgent;
}
set
{
userAgent = string.IsNullOrEmpty(value) ? "Mozilla/4.0 (compatible;);" : value;
}
}
///
/// Создает экземпляр класса
///
/// Поисковой запрос
public GoogleParser(string keyword) : this(keyword, null) { }
///
/// Создает экземпляр класса
///
/// Поисковой запрос
/// Прокси
public GoogleParser(string keyword, WebProxy wp)
{
if (string.IsNullOrEmpty(keyword))
{
throw new Exception("Keyword cannot be null or empty");
}
IgnoreGoogleLinks = true;
SearchKeyword = keyword;
if (linksCount == 0)
{
linksCount = 100;
}
SearchQuery = string.Format(Query, SearchKeyword, linksCount, StartFrom);
Proxy = wp;
}
private WebResponse GetResponse(string url)
{
var request = (HttpWebRequest) WebRequest.Create(url);
try
{
request.Method = "GET";
request.AllowAutoRedirect = false;
request.UserAgent = UserAgent;
if (Proxy != null)
{
request.Proxy = Proxy;
}
return request.GetResponse();
}
catch
{
return null;
}
}
private bool GetResponse()
{
try
{
response = GetResponse(SearchQuery);
if (response == null)
{
return false;
}
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1251)))
{
pageSource = reader.ReadToEnd();
}
return true;
}
catch
{
return false;
}
}
///
/// Есть еще страницы с результатами?
///
///
public bool Read()
{
SearchQuery = string.Format(Query, SearchKeyword, linksCount, StartFrom);
if (string.IsNullOrEmpty(pageSource))
{
if (!GetResponse() || pageSource == null)
{
return false;
}
}
if (pageSource.IndexOf("следующая", StringComparison.OrdinalIgnoreCase) != -1 ||
pageSource.IndexOf("повторить поиск", StringComparison.OrdinalIgnoreCase) != -1)
{
StartFrom += linksCount;
return true;
}
return false;
}
///
/// Забрать результат поискового запроса, равного 1-й пропарсенной странице
///
/// Коллекция ссылок
public List GetResult()
{
if (string.IsNullOrEmpty(pageSource))
{
if (!GetResponse() || pageSource == null)
{
return null;
}
}
var s = new List();
var tmp = new Regex(@"", RegexOptions.IgnoreCase).Matches(pageSource);
foreach (Match m in tmp)
{
var str = m.Value.ToLower();
if (IgnoreGoogleLinks & str.IndexOf("google") > 0)
{
continue;
}
str = str.Remove(0, str.IndexOf("href=") + 5);
str = str.Remove(str.IndexOf(">"));
s.Add(str);
}
pageSource = "";
return s;
}
}