100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > python抓取斗鱼的主播及热度

python抓取斗鱼的主播及热度

时间:2020-07-07 00:09:22

相关推荐

python抓取斗鱼的主播及热度

Python抓取斗鱼主播及热度

刚接触python,想用python爬取下斗鱼的主播及其热度,下面是一个小demo

具体代码如下

from urllib import requestfrom io import BytesIOimport reimport gzipimport sslssl._create_default_https_context = ssl._create_unverified_contextclass Spider():url = '/g_LOL'# [\s\S]字符*0次或多次 ?非贪婪 ([\s\S]*?)root_pattern = '<div class="DyListCover-info">(.*?)</div>' # 匹配所有内容,非贪婪name_pattern = '<use xlink:href="#icon-user_c95acf8"></use></svg>([\s\S]*?)</h2>'number_pattern = '<use xlink:href="#icon-hot_8a57f0b"></use></svg>(.*?)</span>'def __fetch_content(self):r = request.urlopen(Spider.url)htmls = r.read() # 返回bytebuff = BytesIO(htmls)f = gzip.GzipFile(fileobj=buff)htmls = f.read().decode('utf-8')return htmlsdef __analysis(self, htmls):root_html = re.findall(Spider.root_pattern, htmls)# print(root_html) findall返回list# print(type(root_html)) list# print(type(root_html[1])) strroot_html1 = []root_html1 = root_html[1::2] # 取偶数项,切片操作 (数据特殊,必须是第二个孩子)# print(root_html1[1])anchors = []for html in root_html1:name = re.findall(Spider.name_pattern, html) # listnumber = re.findall(Spider.number_pattern, html) # listanchor = {'name': name, 'number': number}anchors.append(anchor)return anchorsdef __refine(self, anchors): # 数据精炼def l(anchor): return {# 返回对象'name': anchor['name'][0].strip(), # strip去空格'number': anchor['number'][0]}return map(l, anchors) # 返回mapdef __sort(self, anchors):anchors = sorted(anchors, key=self.__sort_sead, reverse=True)return anchorsdef __sort_sead(self, anchor): # 配置sort的第二个参数r = re.findall('\d*', anchor['number'])number = float(r[0]) # r[0]匹配的是开头数字if '万' in anchor['number']:number *= 10000return numberdef __show(self, anchors):for rank in range(0, len(anchors)):print('Rank '+str(rank+1)+':' +anchors[rank]['name']+' '+anchors[rank]['number'])def go(self): # 入口文件htmls = self.__fetch_content()anchors = self.__analysis(htmls)anchors = list(self.__refine(anchors))anchors = self.__sort(anchors)self.__show(anchors)spider = Spider()spider.go()

实现效果如下

这是看一个网课视频,跟着老师敲下来的,只是老师用的是熊猫直播,然鹅,当我学的时候,它已经不在了,😂😂,只能根据老师的方法,遇见问题,慢慢查资料,解决问题。

ps:

该demo只适用于了解简单爬数据的步骤,由于数据有一些特殊,对数据的正则表达式会有所不同,不具有普遍性。

代码地址:spider.py

欢迎一起交流学习,嘻嘻!!!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。