HtmlAgilityPack
如何使用我这样做来检索 img 元素的宽度和高度..
HtmlAgilityPack.HtmlAttribute width = link.Attributes["width"];
HtmlAgilityPack.HtmlAttribute height = link.Attributes["height"];
但在大多数情况下,宽度和高度为空。如何获得css的高度和宽度?
HtmlAgilityPack
如何使用我这样做来检索 img 元素的宽度和高度..
HtmlAgilityPack.HtmlAttribute width = link.Attributes["width"];
HtmlAgilityPack.HtmlAttribute height = link.Attributes["height"];
但在大多数情况下,宽度和高度为空。如何获得css的高度和宽度?
此页面中的基础:页面
public sealed class UtilParserHTML
{
//Private Fields
private Uri Uri;
private Stream StreamPage;
private HttpWebRequest HttpRequest;
private HttpWebResponse HttpResponse;
//Public Fields
public HtmlDocument HtmlDocument { private set; get; }
public UtilParserHTML()
{
if (this.HtmlDocument == null)
HtmlDocument = new HtmlDocument();
}
public void LoadHTMLPage(string UrlPage)
{
if (string.IsNullOrEmpty(UrlPage))
throw new ArgumentNullException("");
CookieContainer cookieContainer = new CookieContainer();
this.Uri = new Uri(UrlPage);
this.HttpRequest = (HttpWebRequest)WebRequest.Create(UrlPage);
this.HttpRequest.Method = WebRequestMethods.Http.Get;
this.HttpRequest.CookieContainer = cookieContainer;
this.HttpResponse = (HttpWebResponse)this.HttpRequest.GetResponse();
this.StreamPage = this.HttpResponse.GetResponseStream();
this.HtmlDocument.Load(StreamPage);
}
public void LoadHTMLPage(FileStream StreamPage)
{
if (StreamPage == null)
throw new ArgumentNullException("");
HtmlDocument.Load(StreamPage);
}
public HtmlNodeCollection GetNodesByExpression(string XPathExpression)
{
if (string.IsNullOrEmpty(XPathExpression))
throw new ArgumentNullException("");
return this.HtmlDocument.DocumentNode.SelectNodes(XPathExpression);
}
使用XPath在 html 中导航。在这种情况下,我使用了这个 Xpath 表达式: //div[@class='arrowRibbon'] //img
看: ...
this.ParserHTML.LoadHTMLPage("http://www.img.com.br/default.aspx");
HtmlNodeCollection HtmlNodeCollectionResult = this.ParserHTML.GetNodesByExpression(Page.XPathExpression);
if (HtmlNodeCollectionResult != null)
{
foreach (HtmlNode NodeResult in HtmlNodeCollectionResult)
{
var src = NodeResult.Attributes["src"].Value;
}
}
...
编辑
看看这个带有宽度和高度的完整示例:
this.ParserHTML.LoadHTMLPage("http://www.w3schools.com/tags/tag_img.asp");
HtmlNodeCollection HtmlNodeCollectionResult = this.ParserHTML.GetNodesByExpression("//div[@class='tryit_ex'] //img");
if (HtmlNodeCollectionResult != null)
{
foreach (HtmlNode NodeResult in HtmlNodeCollectionResult)
{
var src = NodeResult.Attributes["src"].Value;
var w = NodeResult.Attributes["width"].Value;
var h = NodeResult.Attributes["height"].Value;
}
}
希望这有帮助。