Python3实现原生爬虫,不用框架,用正则表达式【详细代码+注释】

简单说下我对爬虫的理解,爬虫即对HTML进行文本分析,提取所需内容
在爬虫前,需要明确目的,找到数据对应的网页,并分析网页结构找到数据的标签

要爬的网站是熊猫TV

目的:熊猫TV下,某个游戏下主播的人气排行,爬取主播名字、观看人数

版本是python3.5.2,以学习为主,只使用正则表达式

from urllib import request
import re

class Spider():
    # URL地址
    url = 'https://www.panda.tv/cate/lol'
    # 根据要匹配的标签,确定正则表达式字符串,所有字符[\s\S],出现多次*,非贪婪?到第一个
就结束 # 利用组即加圆括号取得标签中间内容 root_pattern = '
([\s\S]*?)
' # 主播名字 name_pattern = '([\s\S]*?)' # 人数 number_pattern = '([\s\S]*?)' # 解析URL def __fetch_content(self): r = request.urlopen(Spider.url) htmls = r.read() # bytes,需要转换成字符串 htmls = str(htmls, encoding='utf-8') return htmls # 解析HTML def __analysis(self, htmls): root_html = re.findall(Spider.root_pattern, htmls) # print(root_html[0]) anchors = [] for html in root_html: name = re.findall(Spider.name_pattern, html)[0] number = re.findall(Spider.number_pattern, html) anchor = {'name': name, 'number': number} anchors.append(anchor) # print(anchors[0]) return anchors # 精炼,格式化 def __refine(self, anchors): # 去除空格和列表符号 l = lambda anchor: {'name': anchor['name'].strip(), 'number': anchor['number'][0]} return map(l, anchors) # 排序,不能直接对字典进行排序,需要指定要排序的数,降 序 def __sort(self, anchors): return sorted(anchors, key=self.__sort_seed, reverse=True) # 指定字典中要排序的数,将汉字万转换成数字 def __sort_seed(self, anchor): r = re.findall('[\d\.]*',anchor['number']) number = float(r[0]) if '万' in anchor['number']: number *=10000 return number # 显示 def __show(self, anchors): # for anchor in anchors: # print(anchor['name']+'----'+anchor['number']) # 加上排名 for rank in range(0, len(anchors)): print("rank "+str(rank+1)+': '+anchors[rank]['name'] +' '+anchors[rank]['number']) def run(self): htmls = self.__fetch_content() anchors = self.__analysis(htmls) anchors = list(self.__refine(anchors)) anchors = self.__sort(anchors) self.__show(anchors) spider = Spider() spider.run()

以上是完整源代码,如果需要爬取该网站其他游戏主播热度,更换URL即可

最后的运行结果如下图所示
Python3实现原生爬虫,不用框架,用正则表达式【详细代码+注释】_第1张图片

谢谢!!

你可能感兴趣的:(Python)