A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 黄玉昆 黑马帝   /  2013-4-18 20:08  /  5090 人查看  /  13 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

先附上改了一处的毕老师源代码:
  1. public static void getQQMails()throws Exception
  2.         {
  3. //我输入的网址
  4.                 URL url = new URL("http://qun.qzone.qq.com/group#!/107291373/member");

  5.                 URLConnection conn = url.openConnection();

  6.                 BufferedReader bufIn = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  7.                
  8.                 String line = null;

  9.                 String mailreg = "\\(\\d+\\)";
  10.                 Pattern p = Pattern.compile(mailreg);

  11.                
  12. //获取指定字符串
  13.                 while((line=bufIn.readLine())!=null)
  14.                 {
  15.                         System.out.println(line);
  16.                         Matcher m = p.matcher(line);
  17.                         while(m.find())
  18.                         {
  19.                                 System.out.println("---------");//测试用
  20.                                 System.out.println(m.group());
  21.                         }
  22.                 }
  23.         }
复制代码
这个功能我就是想获取网页出现的括号中带数字的内容,如像(1111111)这样规则的字符串。我用打印语句的测试了一下,放在上面的位置就打印不出来了,说明了m.find()这个是false。
然后我有打印了一下读取到的line,打印的信息不知道是些神马东东。请看出问题的童鞋帮帮忙,谢谢,答对者奖励大大的哦。
输出的信息如下:

评分

参与人数 1技术分 +1 收起 理由
滔哥 + 1

查看全部评分

13 个回复

倒序浏览
  1. <!DOCTYPE HTML>
  2. <html lang="zh-cn" class="">
  3. <head>
  4.         <meta charset="UTF-8" />
  5.         <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  6.         <script type="text/javascript">
  7.                 var g_V={qz:'_2.1.1.4',ci:'_915b'},g_iLoginUin = 0,siDomain = 'qzonestyle.gtimg.cn',imgcacheDomain = 'qzs.qq.com',g_UserBitmap="0",g_LoginBitmap="0",g_StyleID="v6/16",g_hasCustomStyle=0,g_diyTitle="",g_diySkin=0,g_SceneID=9,g_StyleID="v6/16",g_fullMode=6,g_Mode="ofp",g_frameStyle=1,g_version=6,g_isFriend=0,g_NowTime=1325145132,g_timestamp=0,g_Dressup={items:[],windows:[]},iv={},g_StaticFlag="0",g_TransparentLevel=0,g_isDirectApp=0,g_isBGScroll=0,ownermode=true,ownerProfileSummary=[],g_fl=0,g_ReadOnly=0,g_Errno=0,g_isOFP="1",g_isHideTitle="0",g_icLayout="0",g_Data={},g_isFromPengYou="",g_isBrandQzone="",g_isFamousQzone="",g_xwMode="",g_needDec=1,g_isFastPav="1",_s_=new Date();
  8.                 window.onerror=function(msg,url,line){var info=[msg,url,line,window.navigator.userAgent].join('|_|');new Image().src='http://badjs.qq.com/cgi-bin/js_report?level=4&bid=142&mid=275014&old=1&msg='+encodeURIComponent(info)+'&'+new Date().getTime();return false;};window.imweb={report:(function(){var mIds=["*",277425,277427,277429,277431,277433,277435,289259,289260,289261,289262,289263,289264,289265,289266,289267,289268,289269,289270,289271,289272,289273,290175,290176];var caches={};var img=new Image();var timer;var reportData=function(){var arr=[];for(var o in caches){arr.push(o+'-'+caches[o].v+'-'+mIds[o]+'_'+caches[o].v);}
  9. img.src='http://jsreport.qq.com/cgi-bin/report?id=142&rs='+arr.join('|_|')+'&r='+Math.random();caches={};};return function(key,num){if(!mIds[key]){return;}
  10. num=parseInt(num)||1;if(!caches[key]){caches[key]={v:num}}else{caches[key].v+=num;}
  11. clearTimeout(timer);timer=setTimeout(reportData,500);};})()}
  12.         </script>
  13.         <script type="text/javascript">
  14.                 document.domain = 'qq.com';
  15.                 var siDomain = 'cnc.qzonestyle.gtimg.cn';
  16.                 var imgcacheDomain = 'cnc.qzs.qq.com';

  17.                 //test
  18.                 var csVar = 'user_platform: imgcache_prefix:cnc. imgcache:qzs.qq.com qzonestyle:qzonestyle.gtimg.cn loginuin:0 uin:0'
  19.                 //

  20.                 var g_V = {
  21.                         qz: '_2.1.27',
  22.                         ci: '_v6_20121217',
  23.                         se: '',
  24.                         gp: ''
  25.                 };
  26.                 var g_iLoginUin = 0;
  27.                 var g_iUin = 0;
  28.                 var g_UserBitmap = '0000000045111eb0';
  29.                 var g_LoginBitmap = '0000000045111eb0';
  30.                 var ownerProfileSummary = [''];

  31.         </script>
  32.         <title>缇ょ┖闂?/title>
  33.         <link href="http://cnc.qzonestyle.gtimg.cn/qzone_v6/gb_toolbar.css?max_age=31536000&d=20130108" rel="stylesheet" />
  34.         <link href="http://cnc.qzs.qq.com/qzone_v6/app_group.css?max_age=31536000&d=20130108" rel="stylesheet" />

  35.         <!--[if IE]><base href="http://cnc.qzs.qq.com/"></base><![endif]-->
  36.         <!--[if !(IE)]><!--><base href="http://cnc.qzs.qq.com/" /><!--<![endif]-->

  37.         <link rel="Shortcut Icon" href="http://cnc.qzonestyle.gtimg.cn/qzone_v6/img/favicon.ico?max_age=31536000" type="image/x-icon" />
  38.        
  39. </head>
  40. <body>

  41. <div>
  42.        
  43.         <script>(function(){if(location.host!='qun.qzone.qq.com'){location.href='http://qun.qzone.qq.com/group';}})();</script><script>(function(){var cache={};this.tmpl=function tmpl(str,data){var fn=!/\W/.test(str)?cache[str]=cache[str]||tmpl(document.getElementById(str).innerHTML):new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};"+"with(obj){p.push('"+
  44. str.replace(/[\r\t\n]/g," ").replace(/'(?=[^%]*%>)/g,"\t").split("'").join("\\'").split("\t").join("'").replace(/<%=(.+?)%>/g,"',$1,'").split("<%").join("');").split("%>").join("p.push('")
  45. +"');}return p.join('');");return data?fn(data):fn;};})();(function(){window.console=window.console||{log:function(){},info:function(){},error:function(){}};window.QWT={data:{},restHTML:function(str){return(str+'').replace(/\/g,"\\").replace(/"/g,'\x22').replace(/'/g,'\x27').replace(/'/g,'\x27').replace(/>/g,'>').replace(/</g,'<').replace(/&/g,'&');},escHTML:function(str){return(str+'').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/\x27/g,''').replace(/\x22/g,'"');},getCookie:function(name){var r=new RegExp("(?:^|;+|\\s+)"+name+"=([^;]*)"),m=document.cookie.match(r);return(!m?"":m[1]);},DJB:function(str){var hash=5381;for(var i=0,len=str.length;i<len;++i){hash+=(hash<<5)+str.charCodeAt(i);}
  46. return hash&0x7fffffff;},getACSRFToken:function(){return QWT.DJB(QWT.getCookie('skey'));},getParameter:function(url,name){var r=new RegExp("(\\?|#|&)"+name+"=([^&#]*)(&|#|$)"),m=url.match(r);return(!m?"":m[2]);},reduceImage:function(trueSrc,ew,eh,options){var img=new Image();img.onload=function(){if(!options.img){window.console&&console.log('鏈寚瀹歩mg');return;}
  47. if(this.width>ew||this.height>eh){this.width>this.height?(this.width=ew):(this.height=eh);}
  48. options.img.onload=null;options.img.src=this.src;options&&options.callback&&options.callback(this);};img.src=trueSrc;},load:function(params){params||(params={});var jsList=params.jsList||[];var cgiList=params.cgiList||[];var jsMaxAge=params.jsMaxAge||0;var jsConcat=!!params.jsConcat||false;var jsString;if(jsConcat){jsString='<script src="http://'+(siDomain||'qzonestyle.gtimg.cn')+'/c/='+jsList.join(',')+(jsMaxAge?'?max_age='+jsMaxAge:'')+'" ><\/script>';}else{jsString='';for(var i=0;i<jsList.length;i++){jsString=jsString+'<script charset="utf-8" src="http://'+(window.siDomain||'qzonestyle.gtimg.cn')+jsList[i]+'" ><\/script>';}}
  49. var cgiString='';for(var j=0;j<cgiList.length;j++){cgiString=cgiString+'<script charset="utf-8" src="http://'+cgiList[j]+'" ><\/script>';}
  50. document.write(jsString+cgiString);},scaleImageByShort:function(trueSrc,ew,eh,options){var img=new Image();img.onload=function(){if(!options.img){return;}
  51. var imgWHRatio=this.width/this.height;var expectWHRatio=ew/eh;if(this.width>ew&&this.height>eh){if(imgWHRatio<=expectWHRatio){options.img.width=ew;}else{options.img.height=eh;}}
  52. options.img.onload=null;options.img.src=this.src;options&&options.callback&&options.callback(this);};img.src=trueSrc;},cut:function(str,bitLen,tails){str=String(str);bitLen-=0;tails=tails||'';if(isNaN(bitLen)){return str;}
  53. var len=str.length,i=Math.min(Math.floor(bitLen/2),len),cnt=QWT.getRealLen(str.slice(0,i));for(;i<len&&cnt<bitLen;i++){cnt+=1+(str.charCodeAt(i)>255);}
  54. return str.slice(0,cnt>bitLen?i-1:i)+(i<len?tails:'');},getRealLen:function(s,isUTF8){if(typeof(s)!='string'){return 0;}
  55. if(!isUTF8){return s.replace(QWT.RegExps.getRealLen.r0,"**").length;}else{var cc=s.replace(QWT.RegExps.getRealLen.r1,"");return(s.length-cc.length)+(encodeURI(cc).length/3);}},RegExps:{getRealLen:{r0:/[^\x00-\xFF]/g,r1:/[\x00-\xFF]/g}}};var clearQWTData=function(){QWT.data={};};if(window.addEventListener){window.addEventListener('load',function(){clearQWTData();});}else if(window.attachEvent){window.attachEvent('onload',function(){clearQWTData();});}else{window.onload=function(){clearQWTData();};}
  56. window.QZONE=window.QZONE||{};QZOmemberCount':g_group_memberCount=value;break;case'bbsCount':bbsCount=value;break;case'createtime':g_group_createtime=value;break;case'totalPhotoCount':g_group_picCount=value;break;case'firstScreenFirstFeedTime':g_group_firstfeedtime=value;break;case'firstScreenLastFeedTime':g_group_lastfeedtime=value;break;case'firstScreenHasMoreFeeds':g_group_hasmorefeeds=value;break;case'firstScreenDupKeys':g_group_dup_keys=value;break;case'isFakeQun':g_group_is_fake_qun=value;break;case'baseLink':baseLink=value;break;case'firstScreenMoreGroups':moreGroups=value;break;}};GroupZone.getConfig=function(key){var data={'groupId':g_group_groupId,'groupName':g_group_groupName,'isMember':g_group_isMember,'isManager':g_group_isManager,'isCreator':g_group_isCreator,'members':g_group_member,'creator':g_group_creator,'groupMemo':g_group_groupMemo,'fingerMemo':g_group_fingerMemo,'firstScreenFirstFeedTime':g_group_firstfeedtime,'firstScreenLastFeedTime':g_group_lastfeedtime,'firstScreenHasMoreFeeds':g_group_hasmorefeeds,'firstScreenDupKeys':g_group_dup_keys,'createtime':g_group_createtime,'totalPhotoCount':g_group_picCount,'shareCount':g_group_shareCount,'loginUin':loginUin,'commentModuleHash':g_group_commentModuleHash,'isFakeQun':g_group_is_fake_qun,'loginNick':loginNick,'bbsCount':bbsCount,'baseLink':baseLink,'firstScreenMoreGroups':moreGroups};var val=key?data[key]:data;return val;};})();(function(){QWT.data['loginUin']='0';GroupZone.setConfig('baseLink','http://qun.qzone.qq.com/group');})();</script><script>(function(){var hash=location.hash;var DEFAULT_GROUP_COUNT=4;var DEFAULT_COUNT=4;if(!hash||!hash.length){hash='#!/portal';}
  57. hash=hash.replace(/^#/,'').replace(/^(!\/)|(!)|(\/)/,'');var fragments=hash.split('\/');var groupId=parseInt(fragments[0],10);if(isNaN(groupId)){GroupZone.setConfig('groupId',0);GroupZone.setConfig('groupName','');QWT.data['entryModule']=fragments[0]||'portal';}else{GroupZone.setConfig('groupId',groupId);GroupZone.setConfig('groupName',groupId);QWT.data['entryModule']=fragments[1]||'home';}
  58. var cgiList=[];var jsList=
复制代码
回复 使用道具 举报
版主的 顶一顶 虽然不会啊!{:soso_e122:}
回复 使用道具 举报
段旭东 发表于 2013-4-18 20:21
版主的 顶一顶 虽然不会啊!

谢谢,嘿嘿
回复 使用道具 举报
好高深那,看不懂就顶一个
回复 使用道具 举报
我以前也研究过一下,与网页源代码的编码有关.你可以这样测试一下,你自己把网页源代码copy成文档,再爬,如果有结果,就肯定是解码问题.老师爬的是他自己建的站.他什么都知道.

评分

参与人数 1技术分 +1 收起 理由
黄玉昆 + 1

查看全部评分

回复 使用道具 举报
嘿嘿,先收藏了,好好研究下。
回复 使用道具 举报
黄玉昆 黑马帝 2013-4-18 23:56:36
8#
陈圳 发表于 2013-4-18 21:03
我以前也研究过一下,与网页源代码的编码有关.你可以这样测试一下,你自己把网页源代码copy成文档,再爬,如果 ...

其实我是想写一个软件,就是直接从网站上获取数据,如果要是复制源代码就太麻烦了。直接输入网址就能获取数据,这个就很方便了,不过谢谢你,提醒我解码的问题。
回复 使用道具 举报
主要有两点
1、网页默认的是utf-8的编码 ,所以需要用utf-8编码读取,这样打印出来的就不会乱码
2、楼主要确定你查的网页是否有(11111)这样的出现,括号也要区分中英文,中文不用\
  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.regex.*;
  4. class Bug
  5. {
  6.         public static void main(String[] args)throws Exception
  7.         {
  8.                 String address="http://bbs.itheima.com/forum.php?mod=viewthread&tid=46444&extra=page%3D1%26filter%3Dauthor%26orderby%3Ddateline%26orderby%3Ddateline";
  9.                 getQQMails(address);
  10.         }

  11.         public static void getQQMails(String address)throws Exception
  12.         {
  13.                 //我输入的网址
  14.                 URL url = new URL(address);

  15.                 URLConnection conn = url.openConnection();
  16.                 //网页默认的是utf-8的编码,所以需要用utf-8编码读取
  17.                 BufferedReader bufIn = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));

  18.                 String line = null;

  19.                 String mailreg = "([0-9]+)";//如果是中文括号不用加\
  20.                 Pattern p = Pattern.compile(mailreg);


  21.                 //获取指定字符串
  22.                 while((line=bufIn.readLine())!=null)
  23.                 {
  24.                         //System.out.println(line);
  25.                         Matcher m = p.matcher(line);
  26.                         while(m.find())
  27.                         {
  28.                                 System.out.println("---------");//测试用
  29.                                 System.out.println(m.group());
  30.                         }
  31.                 }
  32.         }

  33. }
复制代码
通过上面的代码,可以查到现在这个帖子的你写的(11111).

有图有真相
   
回复 使用道具 举报
版主你那个链接的开不了  通过你获取并打印出来的东西来看  那个网页因该是没有(759832473)这样规则的字符串,所以m.find()就是false啦


{:soso_e151:}{:soso_e151:}{:soso_e151:}{:soso_e151:}{:soso_e151:}

评分

参与人数 1技术分 +1 收起 理由
黄玉昆 + 1

查看全部评分

回复 使用道具 举报
丘凤光 发表于 2013-4-19 09:39
版主你那个链接的开不了  通过你获取并打印出来的东西来看  那个网页因该是没有(759832473)这样规则的字符 ...

我已经找到问题了,不是解码的问题,是网页确实没我想要的内容,我发现是网页中存储的还有连接,所以还需要深入查找,有的我们看到的网页上确实存在的,其实在源代码中并没有,而是显示的链接。
谢谢你啊
回复 使用道具 举报
丘凤光 发表于 2013-4-19 09:39
版主你那个链接的开不了  通过你获取并打印出来的东西来看  那个网页因该是没有(759832473)这样规则的字符 ...

我已经找到问题了,不是解码的问题,是网页确实没我想要的内容,我发现是网页中存储的还有连接,所以还需要深入查找,有的我们看到的网页上确实存在的,其实在源代码中并没有,而是显示的链接。
谢谢你啊
回复 使用道具 举报
黄玉昆 发表于 2013-4-19 10:19
我已经找到问题了,不是解码的问题,是网页确实没我想要的内容,我发现是网页中存储的还有连接,所以还需 ...

版主,我也想知道真么让爬虫自动往深处搜索链接中的链接:lol
回复 使用道具 举报
丘凤光 发表于 2013-4-19 10:26
版主,我也想知道真么让爬虫自动往深处搜索链接中的链接

其实最笨的方法就是用循环判断是不是有http这个关键字,或者其他特有的网页关键字,一层一层打开,就如同递归文件一样,不过这样太消耗资源,也不方便。
另一种方式就是麻烦点,但是能保证成功,就是将网页中的内容复制或者保存下来,就可以了。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马