使用html agility pack从c#中的html中提取图像URL并将它们写入xm
发布时间:2020-12-14 23:21:06 所属栏目:资源 来源:网络整理
导读:我是c#的新手,我真的需要帮助解决以下问题.我希望从具有特定模式的网页中提取照片网址.例如,我希望提取具有以下模式name_412s.jpg的所有图像.我使用以下代码从html中提取图像,但我不知道如何调整它. public void Images() { WebClient x = new WebClient();
我是c#的新手,我真的需要帮助解决以下问题.我希望从具有特定模式的网页中提取照片网址.例如,我希望提取具有以下模式name_412s.jpg的所有图像.我使用以下代码从html中提取图像,但我不知道如何调整它.
public void Images() { WebClient x = new WebClient(); string source = x.DownloadString(@"http://www.google.com"); HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); document.Load(source); foreach(HtmlNode link in document.DocumentElement.SelectNodes("//img") { images[] = link["src"]; } } 我还需要在xml文件中写入结果.你能帮帮我吗? 谢谢 ! 解决方法
要限制查询结果,需要向XPath添加条件.例如,// img [contains(@src,’name_412s.jpg’)]会将结果限制为仅包含具有包含该文件名的src属性的img元素.
至于将结果写入XML,您需要创建一个新的XML文档,然后将匹配的元素复制到其中.由于您无法将HtmlAgilityPack节点直接导入XmlDocument,因此您必须手动复制所有属性.例如: using System.Net; using System.Xml; // ... public void Images() { WebClient x = new WebClient(); string source = x.DownloadString(@"http://www.google.com"); HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); document.Load(source); XmlDocument output = new XmlDocument(); XmlElement imgElements = output.CreateElement("ImgElements"); output.AppendChild(imgElements); foreach(HtmlNode link in document.DocumentElement.SelectNodes("//img[contains(@src,'_412s.jpg')]") { XmlElement img = output.CreateElement(link.Name); foreach(HtmlAttribute a in link.Attributes) { img.SetAttribute(a.Name,a.Value) } imgElements.AppendChild(img); } output.Save(@"C:test.xml"); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |