selenium可以运行JavaScript代码,可以用一些JavaScript来辅助编写Selelnium代码。

1.scrollIntoView - 向下拉滚动条,使得某元素可见

IWebElement element = driver.FindElementById("id_of_element");
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);

2.visibility - 把不可见元素设置为可见

IWebElement element = driver.FindElementById("id_of_element");
((JavascriptExecutor)driver).executeScript("arguments[0].style.height='auto'; arguments[0].style.visibility='visible';";, element);

3.scrollTo - 向下滑动100元素

IWebElement element = driver.FindElementById("id_of_element");
((JavascriptExecutor)driver).executeScript("window.scrollTo(0,100)";, element);

4.style.height/weight - 设置某元素的大小

IWebElement element = driver.FindElementById("id_of_element");
((JavascriptExecutor)driver).ExecuteScript("arguments[0].style.height='500px';", element);
((JavascriptExecutor)driver).ExecuteScript("arguments[0].style.width='500px';", element);

5.Click - 用js点击元素

IWebElement element = driver.FindElementById("id_of_element");
((JavascriptExecutor)driver).ExecuteScript("arguments[0].click();", element);

6.window.open() - 打开一个新的窗口

((JavascriptExecutor)driver).ExecuteScript("window.open();");

7. 高亮显示页面元素

public void highlightElement(WebDriver driver, WebElement element) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow; border: 2px solid yellow;");

参考1: scroll-element-into-view-with-selenium
参考2: https://stackoverflow.com/questions/10660291/highlight-elements-in-webdriver-during-runtime
拓展1: selenium实现chrome分屏截图的合并