栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

java爬虫与python爬虫对比

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java爬虫与python爬虫对比

java爬虫与python爬虫的对比:

python做爬虫语法更简单,代码更简洁。java的语法比python严格,而且代码也更复杂

示例如下:

url请求:

java版的代码如下:

public String call (String url){
            String content = "";
            BufferedReader in = null;
            try{
                URL realUrl = new URL(url);
                URLConnection connection = realUrl.openConnection();
                connection.connect();
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"gbk"));
                String line ;
                while ((line = in.readLine()) != null){
                    content += line + "
";
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            finally{
                try{
                    if (in != null){
                        in.close();
                    }
                }catch(Exception e2){
                    e2.printStackTrace();
                }
            }
            return content;
        }

python版的代码如下:

# coding=utf-8
import chardet
import urllib2
url = "http://www.baidu.com"
data = (urllib2.urlopen(url)).read()
charset = chardet.detect(data)
code = charset['encoding']
content = str(data).decode(code, 'ignore').encode('utf8')
print content

正则表达式

java版的代码如下:

public String call(String content) throws Exception {
            Pattern p = Pattern.compile("content":".*?"");
            Matcher match = p.matcher(content);
            StringBuilder sb = new StringBuilder();
            String tmp;
            while (match.find()){
                tmp = match.group();
                tmp = tmp.replaceAll(""", "");
                tmp = tmp.replace("content:", "");
                tmp = tmp.replaceAll("<.*>", "");
                sb.append(tmp + "
");
            }
            String comment = sb.toString();
            return comment;
        }
    } 

python的代码如下:

import repattern = re.compile(正则)
group = pattern.findall(字符串)

更多Python知识,请关注:Python自学网!!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/816454.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号