本文示例使用selenium启动Firefox,并将浏览器窗口最大化,在百度搜索框内输入“HelloWorld”,最后点击搜索按钮。
源代码如下:
package com.selenium.test;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class testGome {
public static void main(String[] args) {
//如果火狐浏览器没有默认安装在C盘,需要制定其路径
//System.setProperty("webdriver.firefox.bin", "D:/Program Files (x86)/Mozilla Firefox/firefox.exe");
System.setProperty("webdriver.firefox.marionette","C:\\Program Files (x86)\\Mozilla Firefox\\geckodriver.exe");
//WebDriver driver=new FirefoxDriver(); C:\Program Files (x86)\Mozilla Firefox
//定义驱动对象为 FirefoxDriver 对象
WebDriver driver = new FirefoxDriver();
//驱动的网址
driver.get("https://www.baidu.com/");
//浏览器窗口变大
driver.manage().window().maximize();
//定位输入框元素
WebElement txtbox = driver.findElement(By.name("wd"));
//在输入框输入文本
txtbox.sendKeys("HelloWorld");
//定位按钮元素
WebElement btn = driver.findElement(By.id("su"));
//点击按钮
btn.click();
//关闭驱动
driver.close();
}
}
注意:可能会遇到一些报错
1. geckodriver.exe没有放到python安装目录下,这一类报错。
2. python demo.py 执行后,找不到文件,说明没有通过cd命令切换到demo.py所在的文件夹路径。
3.打开火狐浏览器了,但是没有获取到url地址
4.火狐浏览器打开且进入百度网页后关闭火狐浏览器时,提示浏览器遇到一个错误,停止运行了
针对 问题 3、4,我这边是通过降低Firefox浏览器的版本(如果遇到一下这类问题或相关浏览器调用问题,可升级或降低 selenium 和 firefox 的版本 进行兼容)
总结:
通过上面代码,和本文,基本了解了如何打开和关闭浏览器。如果想打开IE或者Chrome浏览器,也需要下载对应浏览器的driver.exe文件
① 在chrome 下运行脚本,需要将chromedriver.exe 放在chrome浏览器安装目录下
(同时设置用户环境变量path:C:\Users\xxxxxx\AppData\Local\Google\Chrome\Application;)
②2 在ie 下运行脚本,需要将IEDriverServer.exe 放在ie浏览器安装目录下
(同时设置用户环境变量path:C:\Program Files\Internet Explorer ),如果在调用浏览器遇到浏览器保护模式问题,可打开Ie浏览器–工具–Internet选项–安全–internet/本地intarnet/受信任的站点/受限制站点中的 启用保护模式全部勾选或者全部不选的勾去掉
③ 在firefox下运行脚本,直接调用(默认Python安装路径下,例如我的路径为:D:\Program Files (x86)\Python36\geckdriver.exe)