获取浏览器标签上显示的网站名称?

时间:2015-09-08 17:58:25

标签: java web

如何在浏览器中打开网站时获取显示在选项卡上的内容的字符串表示?让我们说,如果我打开http://www.stackoverflow.com,是否有可能提取" Stack Overflow"字符串,如下所示:

Stack Overflow tab

我对Java实施感兴趣 - java.net.URL似乎没有一种方法。

2 个答案:

答案 0 :(得分:4)

  

我对Java实施感兴趣 - java.net.URL似乎没有一种方法。

java.net.URL不会这样做,不,你需要一个像JSoup这样的HTML解析器。然后,您只需获取title中的head标记的内容。

例如,假设您有一个URL:

Document doc = Jsoup.connect(url).get();
Element titleElement = doc.select("head title").first(); // Or just "title", it's always supposed to be in the head
String title = titleElement == null ? null : titleElement.text();

答案 1 :(得分:0)

在响应中寻找以下模式 -

private static final Pattern TITLE_TAG = Pattern.compile("\\<title>(.*)\\</title>", Pattern.CASE_INSENSITIVE|Pattern.DOTALL);

使用正则表达式解析HTML的另一个解决方案不被认为是好的 -

javax.swing.text.html.HTMLDocument

URL url = new URL('http://yourwebsitehere.com');
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
String title = (String) htmlDoc.getProperty(HTMLDocument.TitleProperty);
System.out.println('HTMLDocument Title: ' + title);