Skip to content

Instantly share code, notes, and snippets.

@JulianDeclercq
Last active December 16, 2023 18:39
Show Gist options
  • Save JulianDeclercq/00d8e9ed7dff25d8d08390a22e0fc35f to your computer and use it in GitHub Desktop.
Save JulianDeclercq/00d8e9ed7dff25d8d08390a22e0fc35f to your computer and use it in GitHub Desktop.
Imdb fetch name by id
internal abstract class Program
{
private static readonly string[] Ids =
{
"nm0636046", "nm0000228", "tt2310332", "tt0113986", "tt0111191", "tt0117705", "tt0120735", "tt0107616",
"tt2058673", "tt0167261", "tt0167404", "tt0069280", "tt0151804", "nm0000142", "tt7829914", "tt5446858",
"tt3748528", "tt5164214", "tt0100122", "tt0088611", "tt0488085", "tt5149528", "tt0416320", "tt0400435",
"tt0091635", "tt3460252"
};
private static async Task Main()
{
var tasks = Ids.Select(GetImdbName);
var results = await Task.WhenAll(tasks);
foreach (var result in results)
Console.WriteLine(result);
}
private static async Task<string> GetImdbName(string id)
{
using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.AcceptLanguage.Add(
new System.Net.Http.Headers.StringWithQualityHeaderValue("en-US"));
var path = id[0] == 't' ? "title" : "name";
var url = $"https://www.imdb.com/{path}/{id}/";
var response = await httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
const string find = "</script><title>";
var idx = content.IndexOf(find, StringComparison.Ordinal);
var endIdx = content[idx..].IndexOf("</title>", StringComparison.Ordinal);
return $"{id} - {content[(idx + find.Length)..(endIdx + idx)].Replace(" - IMDb", "")}";
}
Console.WriteLine($"{id} Error: {response.StatusCode} - {response.ReasonPhrase}");
return $"{id} NOT FOUND";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment