需要您的帮助来构建一个可以用作 Web scraper 的 java/J2EE 应用程序。
这是我对这个项目的想法
在我的应用程序主页中,将有一个文本框,用户可以在其中输入他们想要访问的任何 URL。 单击“开始”按钮后,网页将显示在我的应用程序下,即 URL 将与我的应用程序保持相同。 用户可以在网页上的文本框中输入任何内容,然后单击相应的操作(搜索/提交)。 在该页面的表单提交中,我可以捕获用户放置在文本框中的文本并将其保存在我的数据库中。 就是这样。
现在的问题是,如果我正在查看一些已经可用的基于 Java 的 Web Scrapers(例如 WebHarvest),它们只是捕获 URL 上的预定义字符串。
请帮助我找到一些教程或任何开源应用程序,经过一些修改后可以为我工作
任何帮助将不胜感激。
谢谢。
最佳答案
我将为您提供简单的Java 中的 Selenium WebDriver。然而,您可能会找到所有详细信息here .
import java.io.*;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebScraper {
public WebDriver driver = new FirefoxDriver();
/**
* Open the test website.
*/
public void openTestSite() {
driver.navigate().to("http://testing-ground.scraping.pro/login");
}
/**
*
* @param username
* @param Password
*
* Logins into the website, by entering provided username and
* password
*/
public void login(String username, String Password) {
WebElement userName_editbox = driver.findElement(By.id("usr"));
WebElement password_editbox = driver.findElement(By.id("pwd"));
WebElement submit_button = driver.findElement(By.xpath("//input[@value='Login']"));
userName_editbox.sendKeys(username);
password_editbox.sendKeys(Password);
submit_button.click();
}
/**
* grabs the status text and saves that into status.txt file
*
* @throws IOException
*/
public void getText() throws IOException {
String text = driver.findElement(By.xpath("//div[@id='case_login']/h3")).getText();
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("status.txt"), "utf-8"));
writer.write(text);
writer.close();
}
/**
* Saves the screenshot
*
* @throws IOException
*/
public void saveScreenshot() throws IOException {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("screenshot.png"));
}
public void closeBrowser() {
driver.close();
}
public static void main(String[] args) throws IOException {
WebScraper webSrcaper = new WebScraper();
webSrcaper.openTestSite();
webSrcaper.login("admin", "12345");
webSrcaper.getText();
webSrcaper.saveScreenshot();
webSrcaper.closeBrowser();
}
}
其他一些scrape related tools在 Java 上。
关于javascript - 如何在java中使用网络爬虫获取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33954007/