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

需要用到:
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('(\d+)
.*?alt="(.*?)".*?href="(.*?)' '".*?(.*?).*?(.*?).*?(.*?)' '.*?', 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()

简单爬虫入门爬取哔哩哔哩排行榜_第1张图片

你可能感兴趣的:(python,正则表达式)