我得到了以下代码:
exch.setOnAction(e -> {
for (int i = 0; i < 10; i++) {
BrowserThread.driver.findElement(By.linkText("Premium Exchange")).click();
String strVal = BrowserThread.driver.findElement(By.id("premium_exchange_stock_wood")).getText();
String strVal2 = BrowserThread.driver.findElement(By.id("premium_points")).getText();
int intVal = Integer.parseInt(strVal);
int intVal2 = Integer.parseInt(strVal2);
if (intVal >= 64 && intVal2 >= 1) {
BrowserThread.driver.findElement(By.name("buy_wood")).clear();
BrowserThread.driver.findElement(By.name("buy_wood")).sendKeys("64"); //enter 64 in the 'buy box'
BrowserThread.driver.findElement(By.xpath("//input[@value='Calculate best offer ']")).click(); //click calculate best offer
BrowserThread.driver.findElement(By.xpath("//div[@id='premium_exchange']/div/div[2]/button")).click(); //click buy
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(BrowserTab.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
LogTab.log.appendText("Not enough premium points.\n");
}
if (stop.isPressed()) {
LogTab.log.appendText("Stopped task.\n");
break;
}
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(MarketTab.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
当按下gui上的按钮时,它基本上可以无限刷新网页。
有一个启动循环的按钮(exch)和一个断开循环的按钮(stop)。但我的问题是,gui在浏览器上执行任务时会冻结。这适用于一切,而不仅仅是这个for循环。
例如,我有一个run按钮来打开selenium web浏览器。gui将冻结,直到web浏览器完全加载。
我四处查看,发现我必须使用线程,但我不知道从哪里开始。我试着为浏览器创建一个单独的类,让它在不同的线程上运行,但没有成功,而且我似乎无法找出我做错了什么。
browserthread类:
public class BrowserThread extends Thread {
static WebDriver driver;
private String baseUrl;
private String browsertype;
public BrowserThread(String name, String browsertype) {
super(name);
this.browsertype = browsertype;
}
// set up method to initialize driver object
public void setUp(String browsertype) throws Exception {
if (browsertype.contains("Chrome")) {
System.setProperty("webdriver.chrome.driver","res\\chromedriver.exe");
driver = new ChromeDriver();
} else if (browsertype.contains("PhantomJS")) {
driver = new PhantomJSDriver();
System.setProperty("phantomjs.binary.path", "res\\phantomjs.exe");
} else if (browsertype.contains("PhantomJS Linux")) {
driver = new PhantomJSDriver();
System.setProperty("phantomjs.binary.path", "res/phantomjs.exe");
}
baseUrl = "https://www.google.com/";
driver.get(baseUrl);
}
}
暂无答案!
目前还没有任何答案,快来回答吧!