用python爬取B站在线用户人数

news/2024/7/19 10:52:57 标签: python, json, 爬虫

最近在自学Python爬虫,所以想练一下手,用python来爬取B站在线人数,应该可以拿来小小分析一下

设计思路

首先查看网页源代码,找到相应的html,然后利用各种工具(BeautifulSoup或者直接正则表达式)得到数据, 然后把数据和当且时间保存到本地,并且设置一定的时间间隔,反复得到数据, 不过后面我发现B站在线人数是通过js动态生成的,后面会提到

实现过程

观察HTML网页

打开B站,查看网页源代码
这里写图片描述

我们发现

<div class="online">
    <a href="//www.bilibili.com/video/online.html" target="_blank" title="在线观看:4285260">
        在线人数:3277944
    </a>
    <a href="//www.bilibili.com/newlist.html" target="_blank">
        最新投稿:32678
    </a>
</div>

在线人数是存储在类名为online的div中的a标签,当得到a标签的内容,然后把数字分割出来就可以

提取信息

提取代码片段如下:

url = "https://www.bilibili.com/"
html = get_page_source(url)
#得到网页的string
soup = BeautifulSoup(html, 'html.parser')
viewInfo = soup.find_all('div', attrs={'class': 'online'})[0]
#找到相应div       
numberStr = viewInfo.a.string
#提取标签a的内容
number = str(numberStr.split(':')[1])
#把得到的字符串按照":"来分割所以数字就分到标为1的位置 提取出来就可以

然后发现 我们每次得到的number都为0,这显然是有问题的。

问题的关键在于B站在线人数的数据是动态生成的,这是一个动态的网页,这个数字是通过js代码填进去的,所以我们每次得到的是没经过js处理的HTML,所以需要另外的解决方法

解决问题

这里我们在network里查找关键词online可以找到相应的的api

这里写图片描述

https://api.bilibili.com/x/web-interface/online?callback=jqueryCallback_bili_3&jsonp=jsonp&_=1533639077636

但是打开网址是找不到的, 主要因为我的url是有问题的 把后面的参数去掉就可以访问
得到最后的api网址

https://api.bilibili.com/x/web-interface/online

这里写图片描述

所以后面我们只需要用python解析json, 得到web_online的值就可以了
代码片段如下

url = "https://api.bilibili.com/x/web-interface/online"
html = get_page_source(url)
#获得url的
json_data = json.loads(html)
#解析json
number = (json_data['data']['web_online'])
#得到值

把结果写到txt 以做研究

把当前时间 和 在线人数写到一起,以做研究

with open(fpath, 'a', encoding='utf-8') as f:
    nowTime = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M'))
    f.write(nowTime + "     " + str(number) + '\n')

全部代码

python">import requests
import re
import time
import datetime
from bs4 import BeautifulSoup
import traceback
import json




def get_page_source(url):
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "failed"

def getViewInfo(url, fpath):

    html = get_page_source(url)


    try:
        # soup = BeautifulSoup(html, 'html.parser')
        # viewInfo = soup.find_all('div', attrs={'class': 'online'})[0]
        # viewInfo = soup.find_all('div', attrs={'class':'ebox'})[0]
        # title = viewInfo.p.string
        # print(title)

        # numberStr = viewInfo.a.string
        # number = numberStr.split(':')[1]
        #print(number)

        #使用python来解析json

        json_data = json.loads(html)
        number = (json_data['data']['web_online'])

        #保存文件
        with open(fpath, 'a', encoding='utf-8') as f:
            nowTime = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M'))
            f.write(nowTime + "     " + str(number) + '\n')



    except:
        traceback.print_exc()



def main():
    count = 0
    while 1:
        url = "https://api.bilibili.com/x/web-interface/online"
        #文件路径
        output_path = "G://bilibiliInfo.txt"

        getViewInfo(url, output_path)
        #打印进度
        count = count + 1
        print(count)
        #延时一分钟
        time.sleep(60)


if __name__=="__main__":
    main()

小结

最终可以把此程序 放到服务器上(毕竟电脑也不能总是开着的)
当然在服务器 实现定时运行可以通过crontab 来实现,然后把代码的循环改一下,就能实时监控了!
关于如何在服务器定时运行python可以看这篇博客,还是减少了很多错误的

https://blog.csdn.net/qq874455953/article/details/81586508

这是每隔30分钟的结果部分显示, 仅供参考

这里写图片描述

折线图
这里写图片描述

转载于:https://www.cnblogs.com/qq874455953/p/9589210.html


http://www.niftyadmin.cn/n/512127.html

相关文章

安装python3-pip 出现ubuntu-release-upgrader-gtk : 依赖: update-manager 但是它将不会被安装

Ubuntu 16.04今天安装python3-pip出现 python3-pip : 依赖: python-pip-whl ( 9.0.1-2) 但是它将不会被安装 推荐: build-essential 但是它将不会被安装 推荐: python3-dev (> 3.2) 但是它将不会被安装 推荐: python3-setuptools 但是它将不会被安装 推荐: python3-wheel 但…

纪中2018暑假培训day3提高a组改题记录(混有部分b组)

day3 模拟赛&#xff0c;看了看a组题&#xff0c;发现是博弈论&#xff0c;非常开心&#xff08;因为好玩&#xff09;&#xff0c;于是做的a组。结果差点爆零&#xff0c;死命纠结t1的sg函数&#xff0c;但其实只是一个dp&#xff0c;不用扯到sg函数的那种。 t1&#xff1a; D…

安装ubuntu时候,为什么没有设置root账户的步骤呢?

ubuntu默认root密码不可用&#xff0c;需要用普通用户登录后设置&#xff1a; sudo passwd root提示你输入当前用户的密码&#xff0c;成功后再输入两次密码&#xff0c;这个后输入的就是你设置的root密码 其实一般用的时候只要用一般用户在命令前加上sudo就行了&#xff0c;…

Python的函数, 返回值, 参数

1. 函数 函数是对功能的封装 语法: def 函数名(形参): 函数体(代码块,return) 调用: 函数名(实参)2. 返回值 return:在函数执行的时候, 遇到return 就直接返回,类似于循环里的 break def yue()…

ubuntu系统mysql5.7忘记设置root密码/忘记密码的坑

第一步&#xff0c;修改mysql配置文件让Mysql跳过认证 我的mysql是通过apt install mysql-server 安装的 配置文件目录/etc/mysql/mysql.conf.d/mysql.cnf 编辑mysql.cnf&#xff0c;找到[mysqld] (带英文的中括号)&#xff0c;在下面添加一行 skip-grant-tables 保存退出 …

web项目获取spring的applicationContext方式一

web项目获取spring的applicationContext方式一 package com.sz.util;import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.s…

mac系统用sshpass和ssh混合使用密码登录远程服务器

由于有一些场景不能使用ssh私钥来实现免登&#xff0c;因此需要想其它办法解决一下这个问题。 1.在官网下载源码包 wget http://sourceforge.net/projects/sshpass/files/sshpass/1.06/sshpass-1.05.tar.gz 2.解压 tar xvzf sshpass-1.05.tar.gz 3.编译安装 ./configure ma…

Linux添加新磁盘

如何在虚拟机中为Linux添加新磁盘而不用重启https://jingyan.baidu.com/article/6dad5075320825a123e36ef7.html VM虚拟机扩展磁盘容量并挂区该分区http://blog.csdn.net/liuxd3000/article/details/51700495 虚拟机vmware中无损增加文件系统容量https://jingyan.baidu.com/art…