`
butterfly
  • 浏览: 8760 次
  • 性别: Icon_minigender_1
  • 来自: Sun Yet-sen Universi
最近访客 更多访客>>
社区版块
存档分类
最新评论

关于如何获取网页代码的问题

    博客分类:
  • null
阅读更多
我正在做一个数据挖掘的项目,第一步要把某个网站上的网页的代码下载下来,下面是我写的获取网页代码的程序的源代码:
/**
* Download the file specified by an URL.
*/
package fetchInformation;

import java.io.*;
import java.net.*;

/**
* @author caojinghua
*
*/
public class DownloadFiles {

       public static void LoadFiles(String spec, File save)
      {
try{
    URL url=new URL(spec);
    BufferedReader in=new BufferedReader(new InputStreamReader(url.openStream()));
    //output to a file
    BufferedWriter out=new BufferedWriter(new FileWriter(save));
    String line=null;
    while((line=in.readLine())!=null)
   {
         out.write(line);
   }
   if(in!=null)
         in.close();
   if(out!=null)
out.close();
}catch(MalformedURLException e)
{
     System.out.println(e);
}catch(IOException ioe)
{
     System.out.println(ioe);
}
      }
/**
* @param args
*/
public static void main(String[] args) {
String savepath="a.txt";
String url="http://www.dianping.com/";
try{
File savefile=new File(savepath);
LoadFiles(url, savefile);
}catch(NullPointerException e){
System.out.println(e);
}
}
}

奇怪的是,存储获取到的代码的文件a.txt的内容只有一行:http://www.dianping.com。而若改成获取其他的网站,譬如:url="http://www.google.cn",获取到的内容跟用浏览器查看网页源文件里的内容是一样的,我试过很多网站都没问题,但上面这个网站就不行,不知道是不是该网站要登陆的原因,但用浏览器浏览该网站时是不用登陆的。
分享到:
评论
2 楼 butterfly 2007-01-22  
我按照楼主的blog里写的修改了代码:
URLConnection urlcon=(HttpURLConnection)url.openConnection();
urlcon.setRequestProperty("User-agent", "Firefox/2.0");
BufferedReader in=new BufferedReader(new InputStreamReader(urlcon.getInputStream()));

但抛出java.net.ProtocolException: Server redirected too many  times (20)
1 楼 dengyin2000 2007-01-21  
你可能需要设置请求的user-agent参数.请看我的blog
http://dengyin2000.iteye.com/blog/47414

相关推荐

Global site tag (gtag.js) - Google Analytics