【问题标题】:google search result html code c#google搜索结果html代码c#
【发布时间】:2011-09-26 04:48:48
【问题描述】:
我必须创建一个应用程序,该应用程序将 - 对于给定的术语 - 从 google 搜索页面下载前 10 个结果的链接,但是有一个问题,
如果我使用 webClient 下载源代码,而不是 html,我会得到 JS 代码。
如果我查看 Google chrome (ctrl+u) 中的源代码,我会得到相同的结果,但是如果我尝试使用内置开发人员工具检查该元素,我可以看到真正的 html 代码
谁知道如何下载真正的 html 代码以便提取链接?
【问题讨论】:
标签:
c#
search
google-search
【解决方案1】:
您应该使用 Google 自定义搜索 API
http://code.google.com/apis/customsearch/v1/overview.html
这是一个显示搜索“汽车”的前 10 个结果的示例
<html>
<head>
<title>JSON/Atom Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<script>
function hndlr(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.htmlTitle should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" + item.htmlTitle;
}
}
</script>
<script src="https://www.googleapis.com/customsearch/v1?key=YOUR-KEY&cx=017576662512468239146:omuauf_lfve&q=cars&callback=hndlr">
</script>
</body>
</html>
【解决方案2】:
这是我使用 API 从谷歌获取搜索结果的一些代码:
string googleUriPattern =
"http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=off&rsz=large&userip={0}&q={1}";
var requestUri = new Uri(
string.Format(
googleUriPattern,
"A valid IP address",
"query"
));
var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Timeout = 5000;
using (var webResponse = httpWebRequest.GetResponse())
using (var sr = new StreamReader(webResponse.GetResponseStream()))
{
var result = JsonConvert.DeserializeXNode(sr.ReadToEnd(), "responseData");
var searchResultCount = Convert.ToInt32((string)result.Descendants("estimatedResultCount").FirstOrDefault());
}
如您所见,我的案例是确定 Google 对查询的估计结果计数,但您会得到完整的回复,如果您愿意,可以从中读取结果。
【解决方案3】:
您可以制作一个 Perl 脚本来仅提取您想要的数据,即使它包含大量 JavaScript,该文档也是有效的 HTML,因此您可以使用 HTML 解析器 o 转换为 XHTML 并使用XML::Simple 或 @ 987654322@