简单爬虫入门爬取哔哩哔哩排行榜

需要用到:
requests库
re库

主要步骤:
获取排行榜页面 → 分析html文件写出所需内容的正则表达式 → 匹配出所需内容 → 保存

代码如下(导出的是text文档所以有些空格是为了稍微好看一些)

import json     
import requests
from requests import RequestException
import re

#获取网页
def get_one_page(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None

#解析网页 
def pares_one_page(html, date):
   #正则表达式  .*?表示任意内容 ()中即为提取的内容
    pattern = re.compile('<li.*?"num">(\d+)</div>.*?alt="(.*?)".*?href="(.*?)'
                         '".*?</i>(.*?)</span>.*?</i>(.*?)</span>.*?</i>(.*?)'
                         '</span>.*?</li>', re.S)
    #匹配
    items = re.findall(pattern, html)

#保存
    with open('S:/学习/pycham/哔哩哔哩排行榜/HotBoard.txt', 'a') as f:
        f.write(str(date) + '\n' +
                '排名'+'    '+
                '标题'+'                                               '+
                '网址'+'                                                                    '+
                '播放量'+'    '+
                '热度'+'    '+
                'UP主'+'    '+'\n')
    for item in items:
        print('正在输出', item[0])
        #编码默认gbk 但有些符号无法输出,此处改gb18030
        #''.join() 把数组中元素转为字符串
        with open('S:/学习/pycham/哔哩哔哩排行榜/HotBoard.txt', 'a', encoding='gb18030') as f:
            f.write(''.join(item[0]) +'    ' +
                    ''.join(item[1]) +'        ' +
                    ''.join(item[2]) +'     ' +
                    ''.join(item[3]) +'     ' +
                    ''.join(item[4]) +'     ' +
                    ''.join(item[5]) +'     ' +
                    '\n')
            f.close()


def main():
    url = 'https://www.bilibili.com/ranking?spm_id_from=333.851.b_7072696d61727950616765546162.3'
    date = 2020.4.25
    html = get_one_page(url)
    #print(html)   #正则表达式从此处编写
    pares_one_page(html,date)


main()


结果如图所示

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值