我正在从事一个项目,该项目基本上是为一项特殊的工作做类似网络爬虫的事情,实际上更多是机器人。因此,我之前已经在C#上做到了,但是在某些情况下,我必须在JavaFX上实现它。问题在于该网站有两个部分,而这两个部分实际上是两个框架。当我单击第1帧上的链接时,所需的页面将加载到第2帧上。我尝试使用WebEngine状态属性ChangeListener侦听此加载操作,但尚未触发。我该怎么做?
我在下面编写了代码:
private void ClickLinkOnFrame1() {
Document document = engine.getDocument();
NodeList frames = document.getElementsByTagName("frame");
HTMLFrameElement menuFrame = (HTMLFrameElement) document.getElementsByTagName("frame").item(0);
NodeList anchors = menuFrame.getContentDocument().getElementsByTagName("a");
for (int i = 0; i < anchors.getLength(); i++) {
HTMLAnchorElement anchor = (HTMLAnchorElement) anchors.item(i);
if(anchor.getTextContent().equals("blabla")){
engine.executeScript("frames[1].document.getElementsByTagName('a')[" + i + "].click()");
// So when I clicked the link the page has loaded on second frame,
// which on chrome also changes load state of entire page
engine.getLoadWorker().stateProperty().addListener(new ContinueOnSecondFrame());
}
}
}
ContinueOnSecondFrame类的代码为:
class ContinueOnSecondFrame implements ChangeListener<Worker.State> {
@Override
public void changed(ObservableValue<? extends Worker.State> observable, Worker.State oldValue, Worker.State newValue) {
System.out.println("ContinueOnSecondFrame: " + oldValue + " -> " + newValue);
// Check if this class has been reached or not?(Not reached!!!)
if(newValue == Worker.State.SUCCEEDED){
// Do Something...
engine.getLoadWorker().stateProperty().removeListener(this);
}
}
}