Home > database >  How would I extract an image link from a webpage using c#?
How would I extract an image link from a webpage using c#?

Time:06-15

I have some code already, but let's say I have a picture box in a windows forms app which updates to a random image whenever you click it.

How do I extract an image from a website (e.g. https://prnt.sc/hello1)

The image link is located under in the src=

<img  src="https://image.prntscr.com/image/HENolz07Ty_AA4RwYdZVGg.png" crossorigin="anonymous" alt="Lightshot screenshot" id="screenshot-image" image-id="hello1">

The code I have already is:

var image = "";
pictureBox1.ImageLocation = image;
pictureBox1.Update();

How could I (with only the page page url) find the image on the page and define it to 'image' (preferably using c#)

CodePudding user response:

use AngleSharp to get the page HTML and then select the desired element using various selectors. Then you can use the HttpClient to download the file

using AngleSharp;
using System.Net;

var config = Configuration.Default.WithDefaultLoader();
var address = "https://prnt.sc/hello1";
var context = BrowsingContext.New(config);
var document = await context.OpenAsync(address);
var imgSelector = "#screenshot-image";
var cells = document.QuerySelectorAll(imgSelector);
var imageAddress = cells.First().GetAttribute("src");

var client = new HttpClient();
var stream = await client.GetStreamAsync(imageAddress);

using (var fileStream = File.Create(AppDomain.CurrentDomain.BaseDirectory   @"\img.png"))
{
    stream.CopyTo(fileStream);
}
  • Related