通常在使用Google搜索城市后,右侧会出现维基百科页面的一部分,其中包含图像和 map 。谁能告诉我如何访问该图像?我应该知道怎么下载。
最佳答案
实际上,主图像(与右侧 map 图像一起)很少来自维基百科,因此您无法使用维基百科 API 来获取它。如果您想访问实际的主图像,您可以使用:
private static void GetGoogleImage(string word)
{
// make an HTTP Get request
var request = (HttpWebRequest)WebRequest.Create("https://www.google.com.pg/search?q=" + word);
request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36";
using (var webResponse = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
// get all images with base64 string
var matches = Regex.Matches(reader.ReadToEnd(), @"'data:image/jpeg;base64,([^,']*)'");
if (matches.Count > 0)
{
// get the image with the max height
var bytes = matches.Cast<Match>()
.Select(x => Convert.FromBase64String(x.Groups[1].Value.Replace("\\75", "=").Replace("\\075", "=")))
.OrderBy(x => Image.FromStream(new MemoryStream(x, false)).Height).Last();
// save the image as 'image.jpg'
using (var imageFile = new FileStream("image.jpg", FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
}
}
}
}
这对我有用,并且总是返回实际的主图像(如果存在)。例如,GetGoogleImage("New York")
给我 data:image/jpeg;base64,/9j/4AAQSkZJRg... .
我使用的事实是,从响应的所有 base64 字符串图像中,主图像具有最大高度,因此只需按高度对它们进行排序并选择最后一个即可。如果需要,您还可以在此处检查最小图像高度。需要将 \075
替换为 =
base64's padding .
关于android - 在Google搜索时如何从第一页获取图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32400434/