【資料分析】python分析百度搜尋關鍵詞的頻率

來源:互聯網
上載者:User

標籤:爬蟲   自動化   資料分析   python   基礎   

涉及知識點

    1、抓取資料

    2、分頁爬蟲

規律分析

1、抓取資料,發現每一項都是data-tools標籤

2、分頁分析



代碼

import requestsfrom bs4 import BeautifulSoupimport reimport jsonimport jieba#擷取html頁面資訊def getKeywordResult(keyword, pagenum):    url = 'http://www.baidu.com/s?wd=' + keyword + '&pn=' + pagenum + '0'    try:        r = requests.get(url, timeout=30)        r.raise_for_status()        r.encoding = 'utf-8'        return r.text    except:        return ""#解析並抽取資料def parserLinks(html):    soup = BeautifulSoup(html, "html.parser")    links = []    for div in soup.find_all('div', {'data-tools':re.compile('title')}):        data = div.attrs['data-tools']        d = json.loads(data)        links.append(d['title'])        words_all.append(d['title'])    return links, words_all#詞頻統計def words_ratio(words_all):    words = []    for i in words_all:        tmp = jieba.lcut(i)        for tmp_word in tmp:            words.append(tmp_word)    counts = {}    for word in words:        if len(word) == 1:            continue        else:            counts[word] = counts.get(word, 0) + 1    items = list(counts.items())    items.sort(key=lambda x: x[1], reverse=True)    for i in range(30):        word, count = items[i]        print("{0:<10}{1:>5} 佔比:{2}".format(word, count, int(count)/len(words)))def main():    for pagenum in range(0, 50):        html = getKeywordResult('老張', str(pagenum))#輸入搜尋關鍵詞和頁數        ls, words_all = parserLinks(html)        count = pagenum + 1        for i in ls:            print("[{:^3}]{}".format(count, i))        ls = []    words_ratio(words_all)if __name__ == '__main__':    words_all = []    main()


結果

後續的思考

    代碼都很簡單,高手要懂得如何去擴充。現在雖然資料都爬下來了,但是非常淩亂,仍然需要人工去分析比對。這樣的資料我稱之為裸資料,理想的資料是可讀且有關聯的,我稱之為金子資料。

    這個轉換剖析的過程涉及到兩個問題:

        1、如何?可讀?

              可以用字典裡面的del[]方法刪去壞的資料

        2、如何?資料的關聯性?

              先將裸資料進行二次分析,將相關的字項放到一塊,然後再做運行


【資料分析】python分析百度搜尋關鍵詞的頻率

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.