【发布时间】:2011-03-18 00:01:44
【问题描述】:
我的目标是连接到 OWA 页面(Microsoft Office Outlook Web Access - 基本上是一个电子邮件客户端)并登录,然后阅读加载的新页面并查找收件箱数。
要登录,我需要填写用户名和密码字段并调用某个我知道名称和标题的 JavaScript 函数。
我该怎么做:
- 获取页面的 DOM?
- 更新 DOM 以填写输入文本字段?
- 调用那个 Javascript 函数?
- 获取我被重定向到的页面的新 URL?
到目前为止,我可以使用以下 Java 代码连接到网页并加载其页面源代码:
// open the connection to the welcome page
callback.status("Opening connection...");
URLConnection connection = null;
try
{
connection = url.openConnection();
}
catch(IOException ex)
{
throw new Exception("I/O Problem while attempting URL connection");
}
connection.setDoInput(true);
// open input stream to read website
callback.status("Opening data stream...");
InputStream input = null;
try
{
input = connection.getInputStream();
}
catch(IOException ex)
{
throw new Exception("I/O Problem while opening data stream");
}
// read website contents
callback.status("Reading site...");
String content = "";
byte[] buffer = new byte[100];
int totalBytesRead = 0;
int bytesRead = 0;
try
{
while((bytesRead = input.read(buffer)) != -1)
{
String newContent = new String(buffer, 0, bytesRead);
content += newContent;
}
}
catch(IOException ex)
{
throw new Exception("I/O Problem while reading website");
}
System.out.println(content);
结果是将整个页面源输出到控制台 - 很棒。 我还尝试解析页面以获取 DOM 对象,然后我可以按照该对象查找我的用户名和密码字段:
XMLParserConfiguration config = new XML11DTDConfiguration();
DOMParser parser = new DOMParser(config);
InputSource inputSource = new InputSource(input);
inputSource.setByteStream(input);
try
{
parser.parse(inputSource);
}
catch(SAXParseException ex)
{
}
Document document = parser.getDocument();
visitNode(document, 0);
但我得到一个 SAXParseException::6:62: publicId 和 systemId 之间需要空格。
看起来应该归咎于这条线:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
所以我可能需要以某种方式更改 DOMParser 的配置,以使其足够宽松并“原谅”空白空间要求。
【问题讨论】:
-
我认为您正在从事一个非常困难的项目。该 Javascript 函数将期望在浏览器 DOM 的上下文中执行,您将很难提供该 DOM。找到一种方法来利用 Firefox 或 WebKit 服务器端为您运行页面可能会更容易。
标签: java javascript html dom