簡書7日熱門文章數(shù)據(jù)分析+更新推送(持續(xù)更新···)

簡書7日熱門文章數(shù)據(jù)分析+更新推送(持續(xù)更新···)

工作流程

  1. 爬取簡書7日熱門文章碎税;
  2. 存入MongoDB數(shù)據(jù)庫;
  3. 文章簡單的數(shù)據(jù)分析;
  4. 再次爬取簡書7日熱門文章貌矿;
  5. 判斷新爬取的文章是否與已爬取的內(nèi)容重復(fù);
  6. 如文章不重復(fù)罪佳,發(fā)送郵件提醒逛漫;

URL結(jié)構(gòu)

參考代碼

爬蟲部分代碼

import requests
from lxml import etree

homepage_url = 'http://www.reibang.com'
base_url = 'http://www.reibang.com/trending/weekly'


def get_html(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
    }
    resp = requests.get(url, headers=headers)
    if resp.status_code == 200:
        return resp.text
    else:
        return None


# 解析首頁數(shù)據(jù)
def parse_first_html(html, db):
    root = etree.HTML(html)
    articles = root.xpath('//*[contains(concat( " ", @class, " " ), concat( " ", "content", " " ))]')
    seen_snote_ids = root.xpath('//ul[@class="note-list"]/li/@data-note-id')
    # print(seen_snote_ids)
    for article in articles:
        author = ''.join(article.xpath('div[@class="author"]/div[@class="name"]/a/text()'))
        author_url = homepage_url + ''.join(article.xpath('div[@class="author"]/div[@class="name"]/a/@href'))
        title = ''.join(article.xpath('a[@class="title"]/text()'))
        article_url = homepage_url + ''.join(article.xpath('a[@class="title"]/@href'))
        abstract = ''.join(article.xpath('p[@class="abstract"]/text()')).strip()
        read_and_comments = article.xpath('div[@class="meta"]/a/text()')
        like_and_pay = article.xpath('div[@class="meta"]/span/text()')
        # 數(shù)據(jù)處理
        read_and_comments = ''.join(read_and_comments).strip().split()
        like_and_pay = ''.join(like_and_pay).strip().split()
        # read_count = meta.xpath('a/text()')
        # print(author, author_url, title, article_url, abstract, read_and_comments, like_and_pay)
        # print(''.join(like_and_pay).strip().split())
        data ={
            'author': author,
            'author_url': author_url,
            'title': title,
            'article_url': article_url,
            'abstract': abstract,
            'read_and_comments': read_and_comments,
            'like_and_pay': like_and_pay
        }
        if not is_data_exist(db, data):
            print('保存新數(shù)據(jù)')
            save_data(db, data)
        else:
            print('數(shù)據(jù)已存在酌毡,更新數(shù)據(jù)')
            update_data(db, data)
    return seen_snote_ids


def parse_other_html(html, db):
    root = etree.HTML(html)
    articles = root.xpath('//li/div[@class="content"]')
    seen_snote_ids = root.xpath('//li/@data-note-id')
    # print(seen_snote_ids)
    for article in articles:
        author = ''.join(article.xpath('div[@class="author"]/div[@class="name"]/a/text()'))
        author_url = homepage_url + ''.join(article.xpath('div[@class="author"]/div[@class="name"]/a/@href'))
        title = ''.join(article.xpath('a[@class="title"]/text()'))
        article_url = homepage_url + ''.join(article.xpath('a[@class="title"]/@href'))
        abstract = ''.join(article.xpath('p[@class="abstract"]/text()')).strip()
        read_and_comments = article.xpath('div[@class="meta"]/a/text()')
        like_and_pay = article.xpath('div[@class="meta"]/span/text()')
        # 數(shù)據(jù)處理
        read_and_comments = ''.join(read_and_comments).strip().split()
        like_and_pay = ''.join(like_and_pay).strip().split()
        # read_count = meta.xpath('a/text()')
        # print(author, author_url, title, article_url, abstract, read_and_comments, like_and_pay)
        data ={
            'author': author,
            'author_url': author_url,
            'title': title,
            'article_url': article_url,
            'abstract': abstract,
            'read_and_comments': read_and_comments,
            'like_and_pay': like_and_pay
        }
        if not is_data_exist(db, data):
            print('保存新數(shù)據(jù)')
            save_data(db, data)
        else:
            print('數(shù)據(jù)已存在,更新數(shù)據(jù)')
            update_data(db, data)
    return seen_snote_ids


def get_other_html(url, page, seen_snote_ids):
    url_param = url
    page_param = str(page)
    seen_snote_ids_param = '?seens_snote_ids%5B%5D=' + '?seens_snote_ids%5B%5D='.join(seen_snote_ids)
    url = url + '?page=' + page_param + seen_snote_ids_param
    # print(url)
    return get_html(url)


# 初始化數(shù)據(jù)庫
def init_sql():
    from pymongo import MongoClient
    client = MongoClient('localhost', 27017)
    # 創(chuàng)建數(shù)據(jù)庫sdifen
    db = client.JIANSHU
    return db


# 保存數(shù)據(jù)到數(shù)據(jù)庫中
def save_data(db, data):
    db.WEEKLY.insert(data)


# 更新數(shù)據(jù):刪除原數(shù)據(jù)蕾管,重新保存該數(shù)據(jù)枷踏??掰曾?
def update_data(db, data):
    pass

# 判斷數(shù)據(jù)庫中是否存在數(shù)據(jù)
def is_data_exist(db, data):
    return db.WEEKLY.find({'article_url': data.get('article_url')}).count()

def main():
    db = init_sql()
    resp = get_html(base_url)
    seen_snote_ids = parse_first_html(resp, db) 
    for i in range(2, 15):
        resp = get_other_html(base_url, i, seen_snote_ids)
        seen_snote_ids.extend(parse_other_html(resp, db))


if __name__ == '__main__':
    main()

數(shù)據(jù)分析部分代碼

import pandas as pd
import numpy
import matplotlib.pyplot as plt
# 讀取MongoDB數(shù)據(jù)
def read_data():
    import pymongo
    from pymongo import MongoClient
    client = MongoClient()
    db = client.JIANSHU
    collection = db.WEEKLY
    data = pd.DataFrame(list(collection.find()))
    return data


# 去重旭蠕,文章鏈接一樣的數(shù)據(jù)視為重復(fù)數(shù)據(jù)
data = read_data().drop_duplicates(['article_url'])
userClientCol = ['作者', '文章數(shù)']
# 構(gòu)造DataFrame,注意:需數(shù)組轉(zhuǎn)置
userClientDataFrame = pd.DataFrame(numpy.array([list(set(data.get('author'))), [list(data.get('author')).count(level) for level in list(set(data.get('author')))]]).T, columns=userClientCol)
# 根據(jù)作者文章數(shù)量進(jìn)行排序旷坦,排序方式為降序
userClientDataFrame = userClientDataFrame.sort_values('文章數(shù)', ascending=False)
# 選取文章數(shù)量前20名的作者
userClientDataFrame = userClientDataFrame.head(15)
plt.figure(figsize=(20,10),dpi=100)
labels = list(userClientDataFrame['作者'])
plt.bar(range(len(labels)),userClientDataFrame['文章數(shù)'],tick_label=labels)
plt.title('作者')
plt.show()
發(fā)布文章作者前20名

說明:Mac默認(rèn)的Python或者Anaconda環(huán)境下掏熬,中文會出現(xiàn)亂碼,解決方法如下:

  • 下載微軟雅黑.ttf文件
  • 重命名為DejaVuSans.ttf
  • 替換掉/anaconda/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf(Anaconda環(huán)境)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末塞蹭,一起剝皮案震驚了整個濱河市孽江,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌番电,老刑警劉巖岗屏,帶你破解...
    沈念sama閱讀 218,607評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件辆琅,死亡現(xiàn)場離奇詭異,居然都是意外死亡这刷,警方通過查閱死者的電腦和手機(jī)婉烟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來暇屋,“玉大人似袁,你說我怎么就攤上這事「琅伲” “怎么了昙衅?”我有些...
    開封第一講書人閱讀 164,960評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長定鸟。 經(jīng)常有香客問我而涉,道長,這世上最難降的妖魔是什么联予? 我笑而不...
    開封第一講書人閱讀 58,750評論 1 294
  • 正文 為了忘掉前任啼县,我火速辦了婚禮,結(jié)果婚禮上沸久,老公的妹妹穿的比我還像新娘季眷。我一直安慰自己,他們只是感情好卷胯,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,764評論 6 392
  • 文/花漫 我一把揭開白布子刮。 她就那樣靜靜地躺著,像睡著了一般诵竭。 火紅的嫁衣襯著肌膚如雪话告。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,604評論 1 305
  • 那天卵慰,我揣著相機(jī)與錄音,去河邊找鬼佛呻。 笑死裳朋,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的吓著。 我是一名探鬼主播鲤嫡,決...
    沈念sama閱讀 40,347評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼绑莺!你這毒婦竟也來了暖眼?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,253評論 0 276
  • 序言:老撾萬榮一對情侶失蹤纺裁,失蹤者是張志新(化名)和其女友劉穎诫肠,沒想到半個月后司澎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,702評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡栋豫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,893評論 3 336
  • 正文 我和宋清朗相戀三年挤安,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片丧鸯。...
    茶點(diǎn)故事閱讀 40,015評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡蛤铜,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出丛肢,到底是詐尸還是另有隱情围肥,我是刑警寧澤,帶...
    沈念sama閱讀 35,734評論 5 346
  • 正文 年R本政府宣布蜂怎,位于F島的核電站穆刻,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏派敷。R本人自食惡果不足惜蛹批,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,352評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望篮愉。 院中可真熱鬧腐芍,春花似錦、人聲如沸试躏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽颠蕴。三九已至泣刹,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間犀被,已是汗流浹背椅您。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留寡键,地道東北人掀泳。 一個月前我還...
    沈念sama閱讀 48,216評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像西轩,于是被迫代替她去往敵國和親员舵。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,969評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 前言 以我的理解藕畔,寫一個爬蟲分為以下幾個步驟 分析目標(biāo)網(wǎng)站 訪問單個網(wǎng)頁地址马僻,獲取網(wǎng)頁源代碼 提取數(shù)據(jù) 保存數(shù)據(jù) ...
    青穗黃閱讀 522評論 0 6
  • 本該昨天完成的文章,拖了一天注服【碌耍可能是沒休息好吧措近,昨天的在思路以及代碼處理上存在很多問題,廢話不多說仍秤,我們一起來看一...
    loading_miracle閱讀 5,237評論 2 24
  • 經(jīng)過不斷的修改和嘗試終于成功的獲取到了簡書七日熱門的數(shù)據(jù)熄诡,主要爬取了以下幾個字段:1.用戶2.標(biāo)題3.閱讀量4.評...
    loading_miracle閱讀 852評論 7 9
  • # Python 資源大全中文版 我想很多程序員應(yīng)該記得 GitHub 上有一個 Awesome - XXX 系列...
    aimaile閱讀 26,486評論 6 427
  • 大愿法師:訶五欲不是否定根塵識,而是覺性常在诗力,念念覺照凰浮,不受五塵的影響。根塵相對的時候苇本,既不否定根袜茧,也不否定塵,但...
    AORicky閱讀 1,515評論 2 2