java爬行动物与python爬行动物比较:
python做爬虫语法更容易,代码更简洁。 java的语法比python严格,代码也很复杂
以下是示例。
url请求:
java版的代码如下。
公共字符串调用(字符串URL ) {字符串内容=' '; 缓冲读取程序in=null; try{URLrealurl=newURL(URL; urlconnectionconnection=realurl.open connection (; connection.connect (; in=newbufferedreader (newinputstreamreader (connection.get inputstream )、' gbk ' ); 字符串线; while((line=in.readline ) )!=null ) { content =line 'n '; }catch(exceptione ) { e.printStackTrace ); }finally{try}if(in!=null () { in.close ); }catch(exceptionE2 ) { E2 .打印堆栈跟踪); } }返回内容; } python版的代码如下。
# coding=utf-8 importchardetimporturllib2URL=' http://www.Baidu.com ' data=(ur lib2. urlopen (URL ).read ) ) . decode[code,' ignore ' ].encode [ ' utf8 ' ] printcontent正则表达式
java版的代码如下。
公共字符串调用(字符串内容) throws exception (patternp=pattern.compile (content (3360 ) )、(pattern.com pile ) ) () ); 匹配项=p .匹配项(内容); stringbuilder sb=new stringbuilder (; 字符串tmp; while(match.find () ) { tmp=match.group; tmp=tmp.replaceall(''、''); tmp=tmp.replace('content: ',''); tmp=tmp.replaceall('.* ','); sb .应用程序(tmp (n ); } String comment=sb.toString (; 返回命令; } } python的代码如下。
导入re pattern=re.com pile (正则) group=pattern.findall (字符串) )。