2013-11-26 68 views
0

我想在谷歌图片上执行一个查询来使用htmlagilitypack在c#中获取图片。 为此,我使用一个XPath请求发送到图像使用htmlagilitypack来获取谷歌图片

//*[@id="rg_s"]/div[1]/a/img 

但它无法获取图像的方式。什么可能是这样做的正确方法?

回答

1

以编程方式在其API之外搜索google是违反TOS。考虑Google Custom SearchBing Search API,它们都建立了JSON和SOAP接口。

每个月都可以免费查询数千条查询,并且符合服务的TOS。

编辑:使用Bing API低于C#的例子:

const string bingKey = "[your key here]"; 
var bing = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/")) 
{ 
    Credentials = new NetworkCredential(bingKey, bingKey) 
}; 

var query = bing.Web("Jon Gallant blog", null, null, null, null, null, null, null); 
var results = query.Execute(); 

foreach(var result in results) 
{ 
    Console.WriteLine(result.Url); 
} 
Console.ReadKey(); 

谷歌定制搜索API:

string apiKey = "Your api key"; 
string cx = "Your custom search engine id"; 
string query = "Your query"; 

var svc = new Google.Apis.Customsearch.v1.CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey }); 
var listRequest = svc.Cse.List(query); 

listRequest.Cx = cx; 
var search = listRequest.Fetch(); 

foreach (var result in search.Items) 
{ 
    Response.Output.WriteLine("Title: {0}", result.Title); 
    Response.Output.WriteLine("Link: {0}", result.Link); 
} 
+0

我可以使用apis与c# – aceBox

+0

@aceBox,是的。两者都是可以直接访问或使用提供的客户端访问的HTTP API。这两个注册页面都有示例和文档。 – Mitch

1

你可以试试这个太:在这里,它可以通过获取图像的链接以下

var links = HtmlDocument.DocumentNode.SelectNodes("//a").Where(a => a.InnerHtml.Contains("<img")).Select(b => b.Attributes["href"].Value).ToList(); 
foreach(var link in links) 
    { 
     // you can save the link or do your process here 
    } 
1

谷歌不断发现图像div标签与类。这里是一个查询所有链接到图像:

var links = hdoc.DocumentNode.SelectNodes(@"//div[@class='rg_di']/a") 
       .Select(a => a.GetAttributeValue("href", "")); 
+0

解决方案不起作用。 – aceBox

+0

@ace no it works –

+0

它给出了一个错误:“HtmlAgilityPack.HtmlNodeCollection”不包含选择的定义 – aceBox