是否可以“无浏览器”浏览网站?

时间:2013-11-05 00:13:01

标签: java web

我只是想知道是否可以浏览网站(没有浏览器UI),然后在文本框中输入文本并按下按钮。

是否有任何库可以执行此操作或使用Java中的任何方法连接到站点并输入信息并按下按钮。

1 个答案:

答案 0 :(得分:2)

听起来你正在寻找Selenium

以下是来自Getting Started指南的Google搜索示例:

package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class Example  {
    public static void main(String[] args) {
        // Create a new instance of the html unit driver
        // Notice that the remainder of the code relies on the interface, 
        // not the implementation.
        WebDriver driver = new HtmlUnitDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());
    }
}