谷歌添加了一个很好的功能,可以让你获得任何名人的即时信息,例如,当你搜索“巴拉克奥巴马”时,你会在结果页面上看到个人简介和照片,这样你就不必访问任何结果获取该信息。
现场样本:http: //goo.gl/vf1ti3
我要做的是在即时信息框的左侧获取图像的 URL。我想使用System.Text.RegularExpressions.Regex
HTML 代码来实现这一点。
我可以使用以下代码获取结果页面的来源:
private void getInfoAboutCelebrities()
{
try
{
string celebrityName = null;
Dispatcher.Invoke((Action)delegate()
{
DisableUI();
celebrityName = celebrityName_textBox.Text;
});
celebrityName = HttpUtility.UrlEncode(celebrityName);
string queryURL = "http://www.google.com/search?q=" + celebrityName + "+Height&safe=active&oq=" + celebrityName + "+Height&gs_l=heirloom-serp.12...0.0.0.3140.0.0.0.0.0.0.0.0..0.0....0...1ac..24.heirloom-serp..0.0.0.hXJwfydNFhk";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(queryURL);
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0";
request.Method = "GET";
// make request for web page
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader htmlSource = new StreamReader(response.GetResponseStream());
string htmlStringSource = string.Empty;
htmlStringSource = htmlSource.ReadToEnd();
response.Close();
// Extracting height
var regex = new Regex(@"<span class=""kno-a-v"">(.*?)</span>");
var match = regex.Match(htmlStringSource);
var result = match.Groups[1].Value;
///////////////////////////////////////////////////////////
// Extracting photo ( which I couldn't do it
regex = new Regex(@"data:image/jpeg;base64(.*?)\x3d\x3d");
match = regex.Match(htmlStringSource);
///////////////////////////////////////////////////////////
result = HttpUtility.HtmlDecode(result);
if (String.IsNullOrWhiteSpace(result))
MessageBox.Show("Sorry, no such entry.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
else
{
Dispatcher.Invoke((Action)delegate()
{
preloader_Image.Visibility = Visibility.Hidden;
MessageBox.Show(result);
});
}
Dispatcher.Invoke((Action)EnableUI);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
谁能告诉我应该使用什么正则表达式?(因为实际上我通过查看源代码甚至无法自己获取URL!)