在HTML(Java)中查找值的快速方法 [英] Quick way to find a value in HTML (Java)

查看:187
本文介绍了在HTML(Java)中查找值的快速方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用正则表达式,获取网站HTML并查找此标记内的值(或任何属性的值)的最简单方法是:

Using regular expressions, what is the simplest way to fetch a websites HTML and find the value inside this tag (or any attribute's value for that matter):

<html>
  <head>
  [snip]
  <meta name="generator" value="thevalue i'm looking for" />
  [snip]


推荐答案

取决于多么复杂您需要构建的Http请求(身份验证等)。这是我过去看过的一种简单方法。

Depends on how sophisticated of an Http request you need to build (authentication, etc). Here's one simple way I've seen used in the past.

StringBuilder html = new StringBuilder();
java.net.URL url = new URL("http://www.google.com/");
BufferedReader input = null;
try {
    input new BufferedReader(
        new InputStreamReader(url.openStream()));

    String htmlLine;
    while ((htmlLine=input.readLine())!=null) {
        html.appendLine(htmlLine);
    }
}
finally {
    input.close();
}

Pattern exp = Pattern.compile(
    "<meta name=\"generator\" value=\"([^\"]*)\" />");
Matcher matcher = exp.matcher(html.toString());
if(matcher.find())
{
    System.out.println("Generator: "+matcher.group(1));
}

编译时可能会发现很多拼写错误。
(希望这不是作业)

这篇关于在HTML(Java)中查找值的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆