0

我正在尝试解析页面(任何页面动态解析器​​)。代码是

Elements title = doc.select("title");
Elements metades = doc.select("meta[name=description]");

如您所见,我想提取标题标签。

它在几乎每个网站上都可以正常工作,例如hindroid.com 但它无法从 google.com 和 youtube.com 解析标题我认为这是由于两个标签之间没有空格。大多数大型网站在 html 中没有空间以节省带宽。请建议我 - 我想从网站解析 html。

完整代码:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.regex.*;

import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class post_link extends HttpServlet 
{
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

try 
{
//out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" /><script src=\"http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.3.min.js\"></script><script src=\"jquery-social.js\"></script>");
String linktopro = "http://"+request.getParameter("link_topro");
//String linktopro = "http://hinddroid.com";
Document doc = Jsoup.connect(linktopro).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6").timeout(3000).get();
Elements png = doc.select("img[src]");
Elements title = doc.select("title:first-child");
//Elements title = doc.title();
Elements metades = doc.select("meta[name=description]");
Pattern p1 = Pattern.compile("http://.*|.com*?.(com)");

out.println("<script> var myCars=new Array(");

for(Element pngs : png)
{
Matcher m1 = p1.matcher(pngs.attr("src"));
boolean url = m1.matches();
String baseurl = "";
//out.println(url+"");
if(url)
{ baseurl = ""; }
else
{ baseurl = linktopro; }

out.println("\""+baseurl+""+pngs.attr("src")+"\",");
}
out.println("\"\"");
out.println(");</script>");

String outlink = "<div class=\"linkembox\">"+
"<div class=\"linkembox-img\">"+
"<img src=\"http://hinddroid.com/img/logo.gif\" width=\"150\" height=\"120\" />"+
"<br/><div id=\"linkimg-left\"><</div><div id=\"linkimg-right\">></div>"+
"</div>"+
"<div class=\"linkembox-text\">"+
"<div class=\"h\">"+title.html()+"</div><br/>"+
"<div class=\"h1\">"+metades.attr("content")+"</div>"+
"</div>"+
"</div>";
out.println(outlink);
out.print("<script> left(myCars); </script>");




}
catch(Exception ex)
{
out.print(ex);
} 
finally 
{
out.close();
}

}


}
4

1 回答 1

1

我执行选择器,没关系。一点问题都没有!

public static void main( String[] args ) throws IOException
{
    Document doc = Jsoup.connect("http://facebook.com").get();

    System.out.println("Title: " + doc.title());
    System.out.println("Meta Description: " + doc.select("meta[name=description]").first().attr("content"));

}

使用google.com,您只能获得<title>,而不是<meta name=description...因为它不在 HTML 源代码中。

于 2013-03-01T00:40:10.277 回答