3.Python3网络爬虫
3.1爬虫分析
爬取目的:爬取虎牙TV下,英雄联盟主播的人气排行。
爬取网页:https://www.huya.com/g/lol
分析网页:
(1)如何实现爬取目的:抓取主播名称和直播间观看人数;
(2)查找数据的html:在360浏览器下,按f12查看网页的html信息,点击html中左上角的箭头,在网页中选择主播名称、或观看人数,则会跳转到对应的html。
(3)选择数据对应的标识符:为了能爬取不同主播的名称和人气,必须使用唯一的标识符来提取我们需要的数据。
使用<span class="txt">作为标识符的开始,以</span>作为标识符的结束,则不同主播的标识符相同,因此使用一次正则表达式匹配就可以获得所有主播的名称和人气。
3.2代码编写
步骤:抓取网页html;数据提取;数据精炼和数据排序。
#程序3-1
from urllib import request,parse
import re
class HuYaSpider():
url = 'https://www.huya.com/g/lol'
headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
#使用非贪婪模式,表示匹配到第一个</span>停止
#一级提取
pattern_first = '<span class="txt">([\s\S]*?)</span>\n</li>'
#二级提取:主播名字和主播人气
pattern_name = '<i class="nick" title="([\s\S]*?)">'
pattern_popularity = '<i class="js-num">([\s\S]*?)</i></span>'
#爬取虎牙网页的html信息
def __crawl_web_html(self):
req = request.Request(HuYaSpider.url,headers=HuYaSpider.headers)
htmls = request.urlopen(req).read().decode()
return htmls
#分析htmls,提取数据
def __extract_data(self,htmls):
htmls_first = re.findall(HuYaSpider.pattern_first,htmls)
list_anchors = []
for html in htmls_first:
anchor_name = re.findall(HuYaSpider.pattern_name,html)
anchor_popularity = re.findall(HuYaSpider.pattern_popularity,html)
tup = (anchor_name[0],anchor_popularity[0])
list_anchors.append(tup)
return list_anchors
#数据排序
def __reorder(self,anchors):
#def sorted(iterable, key, reverse)
#iterable:可迭代对象
#key:进行比较的元素
#reverse:默认False,为升序排列;True为降序排列
anchors = sorted(anchors,key=self.__data_process,reverse=True)
return anchors
#sorted会将iterable中的每一个元素传入__data_process中,通过其返回的值进行比较
def __data_process(self,anchor):
number = re.findall('[\d.]*',anchor[1])
number = float(number[0])
if '万' in anchor[1]:
number *= 10000
return number
#主播排名打印
def __anchors_rank(self,anchors):
for anchor in anchors:
print('主播"'+anchor[0]+'"人气:'+anchor[1])
#对象的入口方法
def start(self):
htmls = self.__crawl_web_html()
list_anchors = self.__extract_data(htmls)
anchors = self.__reorder(list_anchors)
self.__anchors_rank(anchors)
lol = HuYaSpider()
lol.start()
运行结果:
主播"星痕OB解说"人气:100.8万
主播"LPL职业联赛"人气:70.5万
主播"火星包"人气:60.0万
主播"MH、金灿毅ChanE"人气:41.2万
主播"大圣归来"人气:16.6万
主播"言帅丶"人气:13.0万
主播"爱拍涛哥剑圣"人气:12.7万
主播"潘神丶"人气:9.1万
主播"楚恒-阿狗"人气:7.2万
主播"LCK冠军联赛"人气:6.9万
主播"阿俊z"人气:4.3万
主播"虎ya丶对象"人气:3.7万
主播"聆听-樊人盖伦"人气:3.7万
主播"AzZ丶小风亚索"人气:3.0万
主播"诺Nuo"人气:2.3万
主播"LOL-S系列赛事"人气:2.3万
主播"飞扬"人气:2.0万
主播"小打野飞仔"人气:1.9万
主播"虎牙TV丶淡忘"人气:1.7万
...