tft每日頭條

 > 科技

 > python爬蟲抓取pc軟件中的數據

python爬蟲抓取pc軟件中的數據

科技 更新时间:2024-09-07 18:59:23

聲明:此文并不是标題黨,如果你不滿18歲,請馬上關閉,在父母陪同下觀看也不行。

數據來源

本文的數據抓取自國内最大的亞文化視頻社區網站(不,不是 B 站),其中用戶出于各種目的會在發帖的标題中加入城市名稱,于是本文抓取了前10000個帖子的标題和發帖用戶 ID,由于按照最近發帖的順序排列,所以抓取數據基本上涵蓋了2016年期間的發帖内容。然後通過匹配提取标題中所包含的城市信息,對16年活躍用戶的歸屬地進行分析統計,另根據最近發布的《2016年中國主要城市 GDP 排名》:

python爬蟲抓取pc軟件中的數據(Python爬取某網站數據分析報告)1

想要學習Python。關注小編頭條号,私信【學習資料】,即可免費領取一整套系統的闆Python學習教程!

檢驗兩者之間是否存在某種程度的相關。

爬蟲

當然本文的目的主要還是出于純粹的技術讨論與實踐,數據抓取和分析處理均使用 Python 完成,其中主要用到的數據處理和可視化工具包分别是Pandas和Plot.ly Pandas。

由于網站使用較傳統的論壇框架,經測試也沒有防爬蟲的措施,因此可以大膽地使用多線程,對于網頁内容分析也可以直接用正則匹配完成:

import requests as req import re from threading import Thread def parser(url): res = req.get(url) html = res.text.encode(res.encoding).decode() titles = re.findall(RE_TITLE, html) v = [] if titles is not None: for title in titles: if len(title) == 2 and title[-1] != 'admin': if title[0][-1] != '>': v.append(title) return v def worker(rag): """ 将每個線程的數據臨時存儲到一個新的文本文件中即可。 """ with open('{} {}.txt'.format(*rag), 'w ') as result: for p in range(*rag): url = ENT_PAT.format(p) for title in parser(url): result.write("{}|{}\n".format(*title)) def main(): threads = [] for i in range(len(SECTIONS)-1): threads.append(Thread(target=worker, args=(SECTIONS[i:i 2],))) for thr in threads: thr.start() if __name__ == '__main__': main()

以上就是爬蟲部分的代碼(當然隐去了最關鍵的網址信息,當然這對老司機們來說并不是問題)。

Pandas

Pandas 可以看做是在 Python 中用于存儲、處理數據的 Excel,與 R 語言中的 data.frame 的概念相似。首先将所有單獨存儲的文件中的數據導入到 Pandas:

import os import pandas as pd title, user = [], [] for root, _, filenames in os.walk('raws'): for f in filenames: with open(os.path.join(root, f), 'r') as txt: for line in txt.readlines(): if line and len(line.split("|")) == 2: t, u = line.split("|") title.append(t) user.append(u.strip()) data = pd.DataFrame({"title": title, "user": user}) # 保存到 csv 文件備用 data.to_csv("91.csv", index=False)

接下來以同樣的方式将國内主要城市數據、2016主要城市 GDP 排行數據加載到 Pandas 中備用。

數據分析

首先需要明确以目前的數據可以探讨哪些有趣的問題:

  • 各個城市的發帖總數;
  • 各個城市的活躍用戶數量;
  • 以上兩個數據結果與 GDP 之間的關系;
  • 發帖形式分類(雖然這個問題的答案可能更有趣,以目前的數據量很難回答這問題,而且需要涉及到較複雜的 NLP,先寫在這裡);
  • 最活躍的用戶來自哪裡。

首先加載備用的數據:

import pandas as pd TABLE_POSTS = pd.read_csv("91.csv") TABLE_CITY = pd.read_csv("TABLE_CITY.csv") TABLE_GDP = pd.read_csv("TABLE_GDP.csv")

匹配标題中是否存在城市的名稱:

# 先替換可能出現的“昵稱” TABLE_POSTS.title = TABLE_POSTS.title.str.replace("帝都", "北京") TABLE_POSTS.title = TABLE_POSTS.title.str.replace("魔都", "上海") def query_city(title): for city in TABLE_CITY.city: if city in title: return city return 'No_CITY' TABLE_POSTS['city'] = TABLE_POSTS.apply( lambda row: query_city(row.title), axis=1) # 過濾掉沒有出現城市名的數據: posts_with_city = TABLE_POSTS.loc[TABLE_POSTS.city != 'No_CITY'] # 以城市名進行 groupby,并按發帖數之和倒序排列: posts_with_city_by_posts = posts_with_city.groupby(by="city").count().sort_values("title", ascending=False)[['title']].head(20)

現在已經可以直接回答第一個問題了,用 Plot.ly 将 Pandas 中的數據可視化出來,有兩種方式,我們選擇較簡單的 cufflinks 庫,直接在 DataFrame 中繪制:

import cufflinks as cf cf.set_config_file(world_readable=False,offline=True) posts_with_city_by_posts.head(10).iplot(kind='pie', labels='city', values='title', textinfo='label percent', colorscale='Spectral', layout=dict( title="City / Posts", width="500", xaxis1=None, yaxis1=None))

python爬蟲抓取pc軟件中的數據(Python爬取某網站數據分析報告)2

前6名基本上不出什麼意外,但是大山東排在第7名,這就有點意思了。為了排除某些“特别活躍”用戶的幹擾,将用戶重複發帖的情況去除,隻看發帖用戶數量:

# 去除 user 欄中的重複數據 uniq_user = posts_with_city.drop_duplicates('user') # 同樣按照城市 groupby,然後倒序排列 posts_with_city_by_user = uniq_user.groupby(by="city").count().sort_values("title", ascending=False)[['title']].head(15) posts_with_city_by_user.head(10).iplot(kind='pie', values='title', labels='city', textinfo='percent label', colorscale='Spectral', layout=dict(title="City / Users", width="500", xaxis1=None, yaxis1=None))

python爬蟲抓取pc軟件中的數據(Python爬取某網站數據分析報告)3

Impressive,山東。至少說明還是比較含蓄,不太願意寫明具體的城市?是這樣嗎,這個問題可以在最後一個問題的答案中找到一些端倪。

接下來要和 GDP 數據整合到一起,相當于将兩個 DataFrame 以城市名為鍵 join 起來:

posts_with_city_by_user_and_gdp = posts_with_city_by_user.merge(TABLE_GDP, left_on='city', right_on='city', how='inner')

python爬蟲抓取pc軟件中的數據(Python爬取某網站數據分析報告)4

由于有些漏掉的排行數據,同時由于人口數據較大,需要進行一定的預處理和标準化處理:

posts_with_city_by_user_and_gdp['norm_title'] = \ posts_with_city_by_user_and_gdp.title/posts_with_city_by_user_and_gdp['pop'] posts_with_city_by_user_and_gdp['norm_rank'] = \ posts_with_city_by_user_and_gdp['rank'].rank() posts_with_city_by_user_and_gdp['x'] = posts_with_city_by_user_and_gdp.index.max() - posts_with_city_by_user_and_gdp.index 1 posts_with_city_by_user_and_gdp['y'] = posts_with_city_by_user_and_gdp['norm_rank'].max() - posts_with_city_by_user_and_gdp['norm_rank'] 1

繪制氣泡圖,氣泡大小為用戶數量與人口數的比,坐标值越大排行越高:

python爬蟲抓取pc軟件中的數據(Python爬取某網站數據分析報告)5

可以看到基本上存在一定程度的相關,但是到這裡我們發現更有趣的數據應該是那些出現在 GDP 排行榜上卻沒有出現在網站排行上的城市,是不是說明這些城市更加勤勞質樸,心無旁骛地撸起袖子幹呢?

good_cities = posts_with_city_by_user.merge(TABLE_GDP, left_o ="city", right_on="city", how="right") good_cities[list(good_cities.title.isnull())][['city', 'rank', 'pop', 'title']]

python爬蟲抓取pc軟件中的數據(Python爬取某網站數據分析報告)6

注:由于 posts_with_city_by_user 隻截取了前15,實際上青島是排在前20的,從下一個結果中就能看出來…

最後一個問題,最活躍的老司機們都來自哪個城市?

user_rank = pd.DataFrame(TABLE_POSTS.user.value_counts().head(20)) user_rank.reset_index(level=0, inplace=True) user_rank.columns = ['user', 'count'] user_rank.merge(posts_with_city[['user', 'city']], left_on='user', right_on='user', how='inner').drop_duplicates(['user','city'])

python爬蟲抓取pc軟件中的數據(Python爬取某網站數據分析報告)7

總結

以上就是全部數據與分析的結果。其實大部分隻是一個直觀的結果展示,既沒有嚴謹的統計分析,也沒有過度引申的解讀。隻有經過統計檢驗才能得出擁有可信度的結論,在一開始已經說明了本文隻是純粹的技術讨論與實踐,所抓取的10000多條數據也隻是網站中某個闆塊,因此對于以上結果不必太過認真。

想要學習Python。關注小編頭條号,私信【學習資料】,即可免費領取一整套系統的闆Python學習教程!

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关科技资讯推荐

热门科技资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved