如何以编程方式获取网页中图像的渲染尺寸?

How to programmatically get the rendered dimensions of an image in a web page?

我需要查询网页中的每个 img 标签,并在呈现形式中找到它的高度和宽度。不是实际的物理图像尺寸。我需要在 WinForm 应用程序中使用 C# 执行此操作。

示例: http://motherboard.vice.com/read/i-built-a-botnet-that-could-destroy-spotify-with-fake-listens

主图的物理尺寸为 3648x2736。当我的浏览器最大化时,渲染图像为 1000x750。我知道媒体查询和图像因它们而调整大小。此 img 标签没有宽度和高度属性。 如何让我的应用程序使用 C# 获得 1000x750 大小并假设最大媒体查询大小和至少 1400 宽度的分辨率。

我假设我需要像 Awesomium, CefSharp, EO.Browser 或 IE Web 浏览器控件这样的浏览器控件?不确定哪个可以做到这一点。我想遍历 img 标签并获取每个渲染标签的尺寸,就好像我打开浏览器并使用开发工具来获取每个图像的计算尺寸一样。与 Javascript.

相比,我更喜欢在 C# 中进行此处理

我一直在用 Selenium WebDriver 进行测试,我认为这是目前最好的选择

我做了一点测试,它按预期工作,这是测试代码

[TestFixture]
public class TestClass
{
    private FirefoxDriver _driver;

    [SetUp]
    public void Setup()
    {
        _driver = new FirefoxDriver();
        _driver.Url = "http://motherboard.vice.com/read/i-built-a-botnet-that-could-destroy-spotify-with-fake-listens";
    }

    [TearDown]
    public void TearDown()
    {
        _driver.Quit();
    }

    [TestCase()]
    public void TestImage()
    {
        IWebElement element = _driver.FindElementByXPath("//img[@class = 'vmp-image' and position() = 1]");

        Assert.IsNotNull(element);

        string width = element.GetCssValue("width");
        string height = element.GetCssValue("height");

        Console.WriteLine("width:  " + width);
        Console.WriteLine("height: " + height);
    }
}

本次测试Selenium WebDriver打开Firefox可以看到网站正在加载,加载后可以访问网站的DOM,甚至可以执行Javascript代码, 通过 XPath、Css、ClassName、TagName 等查找元素...

还要记住这是一个浏览器,你应该最大化或给 window 的浏览器一个特定的大小,因为该网站可能是移动友好的,所以你可以获得不同的图像大小

您也可以使用 Chrome 和 InternetExplorer here is the documentation