Selenium

Selenium是一个用于测试网站的自动化测试工具,支持各种浏览器包括Chrome、Firefox、Safari等主流界面浏览器,同时也支持phantomJS无界面浏览器。chrome也可以开启无界面模式。

关于驱动下载下面
[post cid="112" cover="https://img.uibobo.com/img/python.png"/]

正题

指定文件启动
System.setProperty("webdriver.chrome.driver", "D:\App\chromedrive\chromedriver.exe");
selenium初始化:
HashMap<String, Object> hashMap = new HashMap<>();
//chrome更改文件保存目录(下载)
hashMap.put("download.default_directory","D:\1");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("prefs", hashMap);
//指定请求头
chromeOptions.addArguments("User-Agent:" Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)"");
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
//设置代理ip
chromeOptions.addArguments("--proxy-server=http://127.0.0.1:8081");
//无界面
chromeOptions.addArgument('--headless')
//关闭安全检查
chromeOptions.addArgument("--disable-web-security")
// 关闭界面上的---Chrome正在受到自动软件的控制
chromeOptions.addArguments("--disable-infobars");
//调用chrome扩展来执行自定义js
chromeOptions.addExtensions(new File("D:\webdrivers\mychromeplugin.crx"));
//启动(环境变量方式)
WebDriver driver= new ChromeDriver(chromeOptions);
//自定义窗口大小
Dimension dimension = new Dimension(1920,1080);
driver.manage().window().setSize(dimension);
//url
driver.get("url");
//隐式等待
driver.manage().timeouts().implicitlyWait(10L, TimeUnit.SECONDS);
//页面加载超时
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
//js加载超时
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);

元素等待方法:显示等待

等待条件WebDriver方法
页面元素是否在页面上可用和被点击elementToBeClickable(By locator)
页面元素处于被选中状态elementToBeSelected(WebElement element)
页面元素是否在页面上存在presenceOfElement(By locator)
页面元素是否包含特定文本textToBePresentInElement(By locator)
页面元素值textToBePresentInElementValue(By locator,java.lang.String text)
标题titleContains(java.lang.String title)

例如:new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfElementLocated(By.id(id)));

元素节点查找方法:

driver.findElement(By.className("className"));
driver.findElement(By.cssSelector("#id .className"));
driver.findElement(By.tagName("div"));
driver.findElement(By.xpath("//input[@name='user']"));
driver.findElement(By.name("name"));
driver.findElement(By.linkText("新闻"));
driver.findElement(By.linkText("新"));
driver.findElements(By.xpath("//div"));

执行js代码:

String js="var savePath="c:\a";return savePath;";
JavascriptExecutor driverJs = (JavascriptExecutor) driver;
String fileName = (String) driverJs.executeScript(js);

switchTo(iframe、alert):

driver.switchTo().alert()....;
driver.switchTo().frame("节点");
driver.switchTo().parentFrame()

xpath常用语法:

//table中括号@class='layui-table'中括号[1]//tr[1]//td[6]
//li[contains(text(), '欢迎')]
//input[@onclick='txsbb()']
//input[contains(@onclick,'tjsbjl()')]

鼠标悬停

Actions action = new Actions(driver);
action.moveToElement(SeleniumUtil.waitDomById(driver,"id")).perform();

技巧

selenium下载图片方法

python 有工具包(右键点击)。。。

java 可以通注入执行js保存,或者getCookie通过http请求保存,推荐js注入。

function download(url, fileName, type) {
  let xhr = new XMLHttpRequest();
  xhr.open('get', url, true);
  xhr.setRequestHeader("Content-type", `application/${type}`);
  xhr.responseType = "blob";
  xhr.onload = function () {
    if (this.status == 200) {
      var blob = this.response;
      downloadNormalFile(blob, fileName)
    }
  }
  xhr.send();
}

页面加载时间过长

JavascriptExecutor driverJs = (JavascriptExecutor) driver;
driverJs.executeScript("window.stop();");

Q.E.D.