何使用C#使用HtmlAgilityPack和XPath从网页中

何使用C#使用HtmlAgilityPack和XPath从网页中

本文介绍了如何使用C#使用HtmlAgilityPack和XPath从网页中提取图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。



我一直致力于一个项目,要求我将网站上的特定图像归零,并将其粘贴到WinForms PictureBox中。我已经安装了HtmlAgilityPack,我有我需要的图像的XPath。如何使用C#从网上提取此图像并将其放入PictureBox?



感谢您的时间。

Hello everyone.

I've been working on a project that requires me to zero in on a specific image on a website and stick it into a WinForms PictureBox. I have installed the HtmlAgilityPack, and I have the XPath for the image I need. How can I use C# to pull this image from the web and put it in a PictureBox?

Thank you for your time.

推荐答案

var htmlDocument = new HtmlWeb().Load("URL of website you are targeting...");
var imageNode = htmlDocument.DocumentNode.SelectSingleNode("XPath of image you are targeting...");
string imagePath = imageNode.Attributes["src"].Value;

var imageStream = HttpWebRequest.Create(imagePath).GetResponse().GetResponseStream();
this.pictureBox1.Image = Image.FromStream(imageStream);



现在我需要指出关于 imagePath 的一件事,在上面的代码片段中,我只是阅读了图片的 src 属性并创建了一个Web请求对于它,但实际上,图像的 src 属性更可能包含相对路径,所以在这种情况下你需要制作 imagePath 进入绝对路径,因为否则 HttpWebRequest.Create(imagePath)将失败。


Now I need to point out one thing regarding the imagePath, in the snippet above I just read the image's src attribute and create a web request for it, but in reality it is more likely that the image's src attribute will contain relative path so in that case you would need to make that imagePath into an absolute path because otherwise HttpWebRequest.Create(imagePath) will fail.


这篇关于如何使用C#使用HtmlAgilityPack和XPath从网页中提取图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 00:11