python入门与进阶篇(七)之原生爬虫

爬取熊猫tv lol游戏主播人气排名:

# 爬虫前奏:

# 1.明确目的

# 2.找到数据对应的网页

# 3.分析网页的结构找到数据所在的标签位置

# 模拟HTTP请求,向服务器发送这个请求,获取到服务器返回给我们的HTML

# 用正则表达式提取我们要的数据(名字,人气)

#Vscode断点调试:
# 1.F5开启断点调试
# 2.F11单步调试

#BeautifulSoup 工具库   Scrapy 爬虫框架  
#爬虫 反爬虫 反反爬虫 ip封闭 代理ip

#python内置的爬虫获取库 request
from urllib import request
# 引入正则表达式re模块
import re

class Spider():
    url='https://www.panda.tv/cate/lol'
    # ?非贪婪模式 只要匹配到就好 ()只要中间的
    root_pattern='<div class="video-info">([\S\s]*?)</div>'
    name_pattern='</i>([\s\S]*?)</span>'
    number_pattern='<span class="video-number">([\s\S]*?)</span>'

    #私有方法 获取网页html
    def __fetch_content(self):
        r=request.urlopen(Spider.url)
        #bytes
        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)
        anchors=[]
        for html in root_html:
            name=re.findall(Spider.name_pattern,html)
            number=re.findall(Spider.number_pattern,html)
            anchor={'name':name,'number':number}
            anchors.append(anchor)
        print(anchors[0])
        return anchors
    
    #数据精炼
    def __refine(self,anchors):
        #strip() 去除字符串首尾空格、换行
        l=lambda anchor:{
            "name":anchor['name'][0].strip(),
            "number":anchor['number'][0]
        }
        return map(l,anchors)

    # 排序
    def __sort(self,anchors):
        #sorted() 排序方法
        anchors=sorted(anchors,key=self.__sort_seed,reverse=True)
        return anchors

    # 排序的key
    def __sort_seed(self,anchor):
        r=re.findall('\d*\.?\d*',anchor['number'])
        number=float(r[0])
        if '万' in anchor['number']:
            number=number*10000
        return number

    # 展示排名
    def __show(self,anchors):
        for i in range(0,len(anchors)):
            print("rank:"+str(i+1)+"----name:"+anchors[i]['name']+"---number:"+anchors[i]['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()




猜你喜欢

转载自blog.csdn.net/qq_40083134/article/details/82960596