JAVA爬取b站用户数据

用到的jar包
链接:https://pan.baidu.com/s/1UYi1fcrNc8xNoTdXsipsPw
提取码:csdn

使用的数据库为MySQL



工具类通过mid获得User包装类对象,以及将User类写入数据库

//工具类通过mid获得User包装类对象,以及将User类写入数据库
public class MidUtil {
    //通过mid获取User
    public static User getUser(int mid){
        User user = null;
        String following =null;
        String follower=null;
        String name =null;
        JsonObject userInformation = loadJson("https://api.bilibili.com/x/relation/stat?vmid="+mid);
        if("\"0\"".equals(userInformation.get("message").toString())){
            JsonObject Json_follow = StringToJsonObject(userInformation.get("data").toString());
            //获取关注数
            following = Json_follow.get("following").toString();
            //获取粉丝数
            follower = Json_follow.get("follower").toString();
        }
        JsonObject userName = loadJson("https://api.bilibili.com/x/space/acc/info?mid="+mid);
        if("\"0\"".equals(userName.get("message").toString())){
            JsonObject Json_name = StringToJsonObject(userName.get("data").toString());
            //包装User类
            name = Json_name.get("name").toString();
        }
        user = new User(mid,name,Integer.parseInt(following),Integer.parseInt(follower));
        return user;
    }
    //通过url获取JsonObject
    public static JsonObject loadJson (String url) {
        StringBuilder json = new StringBuilder();
        Gson g = new Gson();
        try {
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"utf-8"));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return g.fromJson(json.toString(), JsonObject.class);
    }
    //将String转为JsonObject
    public static JsonObject StringToJsonObject(String text){
        Gson g = new Gson();
        JsonObject jsonObject = g.fromJson(text, JsonObject.class);
        return  jsonObject;
    }
    //将User信息添加到数据库
    public static void addToDatabase(User[] user,String DatabaseName){
        JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
        String sql = "insert into "+DatabaseName+" values ";
        sql=sql+"("+user[0].getMid()+","+user[0].getName()+","+user[0].getFollowing()+","+user[0].getFollower()+")";
        for(int i=1;i<100;i++){
            sql= sql+",("+user[i].getMid()+","+user[i].getName()+","+user[i].getFollowing()+","+user[i].getFollower()+")";
        }
        template.update(sql);
    }
}

主程序,通过调用工具类达到目的

//主程序,通过调用工具类达到目的
ublic class bilibili {
    public static void main(String[] args) {
        int mid=1;
        User[] user=new User[100];
        //粗略估算b站用户约为703200000
        while(mid<703200000){
        	//每次插入一百条数据
            for(int i = 0 ;i<100;i++){
                user[i] = MidUtil.getUser(mid);
                //数据输出以便监控
                System.out.println(user[i]);
                mid++;
            }
            MidUtil.addToDatabase(user,"user");
        }
    }
}

数据库连接工具类,采用Druid数据库连接池,简化数据库连接,提高效率

//数据库连接工具类,采用Druid数据库连接池,简化数据库连接,提高效率
public class JDBCUtils {
    private static DataSource ds;

    static{
        Properties pr = new Properties();
        try {
            //加载配置文件
            pr.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //获取DataSource
            ds = DruidDataSourceFactory.createDataSource(pr);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接池(DataSource)
    public static DataSource getDataSource(){
        return ds;
    }
    //获取连接
    public static Connection getConnection() throws SQLException {
            return ds.getConnection();
    }
    //关闭资源
    public static void close(Statement state, Connection conn){
        if(state!=null){
            try {
                state.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }
    }
    public static void close(ResultSet rs, Statement state, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        close(state,conn);
    }
}

User包装类

public class User {
    private int mid;
    private String name;
    private int following;
    private int follower;

    public User(int mid, String name, int following, int follower) {
        this.mid = mid;
        this.name = name;
        this.following = following;
        this.follower = follower;
    }

    public int getMid() {
        return mid;
    }

    public void setMid(int mid) {
        this.mid = mid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getFollowing() {
        return following;
    }

    public void setFollowing(int following) {
        this.following = following;
    }

    public int getFollower() {
        return follower;
    }

    public void setFollower(int follower) {
        this.follower = follower;
    }

    @Override
    public String toString() {
        return "User{" +
                "mid=" + mid +
                ", name='" + name + '\'' +
                ", following=" + following +
                ", follower=" + follower +
                '}';
    }
}

主体程序以上。



为增加运行效率可采取多线程

//线程
public class bilibiliThread implements Runnable{
    int mid=1;
    Object obj = new Object();
    @Override
    public void run() {
        User[] user=new User[100];
        while(mid<703200000){
            synchronized (obj){
                for(int i = 0 ;i<100;i++){
                    user[i] = MidUtil.getUser(mid);
                    //数据输出以便监控
                    System.out.println(user[i]);
                    mid++;
                }
                MidUtil.addToDatabase(user,"user");
            }
        }
        
    }
}

主程序

public class Test {
	//线程数
 	int ThreadNumber = 4;
    public static void main(String[] args) {
        bilibiliThread bt = new bilibiliThread();
        Thread[] threads =new Thread[ThreadNumber ];
        for (int i =0;i<ThreadNumber ;i++){
            threads[i] =new Thread(bt,"线程"+(i+1));
            threads[i].start();
        }
    }
}

给大家一些抓到的b站的API
//用户名 会员状态 简介 头像 风纪委员状态等 
https://api.bilibili.com/x/space/acc/info?mid=UID
//粉丝数 关注数 等
https://api.bilibili.com/x/relation/stat?vmid=UID
//总观看量 总获赞数 文章获赞数等
https://api.bilibili.com/x/space/upstat?mid=UID
//视频详细数据
https://api.bilibili.com/x/web-interface/archive/stat?aid=AV号
https://api.bilibili.com/x/web-interface/view?bvid=BV号
//视频评论
http://space.bilibili.com/ajax/member/getSubmitVideos?mid=AV号&;pagesize=单页显示数&page=页数


https://www.bilibili.com/robots.txt
b站允许爬取的页面,建议遵守协议

(博主已经被b站屏蔽IP了)

### 实现B视频爬虫的关键要素 为了实现一个高效的B视频爬虫,可以借鉴已有的经验和最佳实践。以下是构建此类爬虫所需考虑的主要方面: #### 1. 数据获取方式的选择 对于网页内容的提取,通常有两种方法:一种是通过发送HTTP请求直接解析HTML文档;另一种则是利用API接口进行数据调用。考虑到目标平台的安全机制,建议优先尝试官方提供的开放API服务[^2]。 #### 2. 处理反爬措施 为了避免被检测为恶意访问而遭到封锁IP地址的情况发生,在设计过程中应当加入适当的延时处理逻辑,并模拟真实用户的浏览行为模式,比如随机化请求间隔时间和设置合理的并发数量等策略来降低触发频率限制的风险[^3]。 #### 3. 提取所需信息 针对具体要抓取的内容——即视频页面中的`iframe`嵌入代码、标题以及封面图链接,可以通过正则表达式匹配或者借助第三方库(如Jsoup)来进行DOM树结构分析从而精准定位这些元素的位置并读取出其属性值[^1]。 ```java Document doc = Jsoup.connect(url).get(); Elements iframeTags = doc.select("iframe"); String srcAttr = iframeTags.attr("src"); Element titleTag = doc.getElementsByClass("video-title").first(); String videoTitle = titleTag.text(); Element coverImageTag = doc.getElementById("cover-image-id"); // 假设存在这样的ID用于标识封面图片 String imageUrl = coverImageTag.attr("data-src"); ``` #### 4. 存储至数据库 当收集到足够的记录之后,就需要将其持久化保存下来以便后续查询使用。这里推荐采用批量插入的方式提高效率,同时注意合理规划表结构以适应实际应用场景的需求。 ```sql INSERT INTO videos (title, iframe_code, image_url) VALUES (?, ?, ?); // 使用PreparedStatement预编译SQL语句,并传入参数列表执行批量化操作 ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值