C#: Build a Sailboat Search Tool
Example of how you can use C# to query a specific website for sailboats in Florida and parse the results to display clickable links. In this example, we'll use the website "exampleboats.com" as the target website to search for sailboats in Florida.
Before you start, you'll need to install the HtmlAgilityPack NuGet package for HTML parsing.
Open Visual Studio
Create a new Console App (.NET Core) project
Right-click on the project and click 'Manage NuGet Packages...'
Search for 'HtmlAgilityPack' and install it
Now, replace the content of the 'Program.cs' file with the following code:
csharp
Copy code
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using HtmlAgilityPack;
namespace SailboatSearch
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Searching for sailboats in Florida...");
var url = "https://www.exampleboats.com/search?location=florida&type=sailboat";
var web = new HtmlWeb();
var doc = await web.LoadFromWebAsync(url);
var sailboatLinks = doc.DocumentNode
.SelectNodes("//div[contains(@class, 'sailboat-listing')]//a[@href]")
.Select(node => node.Attributes["href"].Value)
.Distinct()
.ToList();
if (sailboatLinks.Count > 0)
{
Console.WriteLine($"Found {sailboatLinks.Count} sailboats:");
foreach (var link in sailboatLinks)
{
Console.WriteLine($"- {link}");
}
}
else
{
Console.WriteLine("No sailboats found.");
}
Console.ReadLine();
}
}
}
Please note that this example uses a fictional website "exampleboats.com" as the target website. You'll need to replace it with the actual website you want to search for sailboats in Florida, and update the XPath expressions to match the HTML structure of that website.
This code snippet demonstrates how to make an HTTP request to a website, load the HTML content, and parse it using XPath to extract the sailboat listing URLs. The links are then displayed in the console as clickable links.
Comments
Post a Comment