来自上下文 Web 搜索引擎的 Web 搜索 API



如何在C#或Python中解析从上下文Web搜索api返回的JSON响应? (这是请求的链接:http://contextualwebsearch.com/freeapi(

下面是 C# 中用于使用 RapidAPI 市场使用 API 的代码。

/// <summary>
/// Performs a Web search and return the results as a SearchResult.
/// </summary>
private static void MaShapeParsingExample()
{
// **********************************************
// *** Update or verify the following values. ***
// **********************************************
//Step 1. Replace the following string value with your valid X-Mashape-Key key.
string Your_X_Mashape_Key = "OV5vB1qRFnmsh2GYXgVtmjbIfLzup1JXrVjjsntqzb3T25JWCA";
//Step 2. The query parametrs:
int count = 10; //the number of items to return
string q = "Donald Trump"; //the search query
bool autoCorrect = true; //autoCorrectspelling
//Step 3. Perform the Web request and get the response
var response = Unirest.get(string.Format("https://contextualwebsearch-websearch-v1.p.mashape.com/api/Search/WebSearchAPI?q={0}&count={1}&autocorrect={2}", q, count, autoCorrect))
.header("X-Mashape-Key", Your_X_Mashape_Key)
.header("X-Mashape-Host", "contextualwebsearch-websearch-v1.p.mashape.com")
.asJson<string>();
//Step 4. Get the ResponseBody as a JSON
dynamic jsonBody = JsonConvert.DeserializeObject(response.Body);
//Step 5. Parse the results
//Get the numer of items returned
int totalCount = (int)jsonBody["totalCount"];
//Get the list of most frequent searches related to the input search query
List<string> relatedSearch = JsonConvert.DeserializeObject<List<string>>(jsonBody["relatedSearch"].ToString());
//Go over each resulting item
foreach (var webPage in jsonBody["value"])
{
//Get The web page metadata
string url = webPage["url"].ToString();
string title = webPage["title"].ToString();
string description = webPage["description"].ToString();
string keywords = webPage["keywords"].ToString();
string provider = webPage["provider"]["name"].ToString();
DateTime datePublished = DateTime.Parse(webPage["datePublished"].ToString());
//Get the web page image (if exists)
string imageUrl = webPage["image"]["url"].ToString(); //get the webpage image url
int imageHeight = (int)webPage["image"]["height"]; //get the webpage image height
int widthHeight = (int)webPage["image"]["width"]; //get the webpage image width
//An example: Output the webpage url, title and published date:
Console.WriteLine(string.Format("Url: {0}. Title: {1}. Published Date:{2}.",
url,
title,
datePublished));
}
}

最新更新