如何使用VBA和Selenium在IE网站上截图特定ID

时间:2018-09-12 14:25:37

标签: excel vba excel-vba selenium screenshot

我正在尝试截取特定ID的屏幕快照,该ID包含一周的天气预报表格(https://forecast.weather.gov/MapClick.php?lat=41.8843&lon=-87.6324#.W5kg1ehKiUk,并且该ID为“七天预报的身体”) 但是我的代码似乎不起作用,并且我发现了一些VBA特定的示例。这就是我的工作。非常感谢,谢谢。

Sub seleniumtutorial()

Dim bot As New WebDriver

bot.Start "IE", "https://forecast.weather.gov/MapClick.php?lat=41.8843&lon=-87.6324#.W5kg1ehKiUk"

bot.Get "/"

bot.FindElementById("seven-day-forecast-body").SaveAs (ActiveWorkbook.Path + "/chicago.jpg")

bot.Quit

End Sub

1 个答案:

答案 0 :(得分:0)

语法是

bot.TakeScreenshot.SaveAs ActiveWorkbook.Path + "/chicago.jpg"

如果您需要调整大小以仅获得屏幕的那部分,则需要裁剪屏幕截图图像。请在here的搜索中查看答案here和VBA示例,以获取指针。

您可以使用硒的滚动功能将图像居中放置在特定元素上。


将元素滚动到中心:

Option Explicit
Sub seleniumtutorial()

    Dim bot As New WebDriver

    bot.Start "IE", "https://forecast.weather.gov/MapClick.php?lat=41.8843&lon=-87.6324#.W5kg1ehKiUk"

    bot.get "/"

    Dim element As Object
    Set element = bot.FindElementById("seven-day-forecast-body")

    Dim scrollElementIntoMiddle As String
    scrollElementIntoMiddle = "var viewPortHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);" _
                            + "var elementTop = arguments[0].getBoundingClientRect().top;" _
                            + "window.scrollBy(0, elementTop-(viewPortHeight/2));"

    bot.ExecuteScript scrollElementIntoMiddle, element

    bot.TakeScreenshot.SaveAs ActiveWorkbook.Path + "/chicago.jpg"

    bot.Quit

End Sub

替代方法是:

bot.ExecuteScript "arguments[0].scrollIntoView();", element