慕課學(xué)習(xí)爬蟲(chóng)實(shí)戰(zhàn)

爬蟲(chóng)前奏:

明確目的;

找到數(shù)據(jù)對(duì)應(yīng)的網(wǎng)頁(yè);

分析網(wǎng)頁(yè)的結(jié)構(gòu)找到數(shù)據(jù)所在的標(biāo)簽位置


模擬HTTP請(qǐng)求,向服務(wù)器發(fā)送這個(gè)請(qǐng)求,獲取到服務(wù)器返回給我們的HTML

用正則表達(dá)式提取我們要的數(shù)據(jù)(名字,人氣)

import re

from urllib import request

class Spider():

? ? url = 'https://www.panda.tv/cate/lol'

? ? root_pattern = r'<div class="video-info">([\s\S]*?)</div>'

? ? name_pattern = r'</i>([\s\S]*?)</span>'

? ? # number_pattern = '<span class="video-number">([\s\S]*?)</span>'

? ? number_pattern = r'<i class="video-station-num">([\s\S]*?)</i>'

? ? #私有方法

? ? def __fetch_content(self):

? ? ? ? r = request.urlopen(Spider.url)

? ? ? ? htmls = r.read()

? ? ? ? htmls = str(htmls,encoding='utf-8')

? ? ? ? return htmls

? ? 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):

? ? ? ? l = lambda anchor : {

? ? ? ? ? ? 'name':anchor['name'][0].strip(),

? ? ? ? ? ? 'number':anchor['number'][0]

? ? ? ? ? ? }

? ? ? ? return map(l,anchors)

? ? def __sort(self,anchors):

? ? ? ? anchors = sorted(anchors,key=self.__sort_seed,reverse=True)

? ? ? ? return anchors

? ? def __sort_seed(self,anchor):

? ? ? ? r = re.findall(r'\d*',anchor['number'])

? ? ? ? number = float(r[0])

? ? ? ? if '萬(wàn)' in anchor['number']:

? ? ? ? ? ? number *= 10000

? ? ? ? return number

? ? def __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()

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容