美文网首页python_pycham以后看蜂采
Python爬取某网站数据分析报告,不满十八岁禁止观看

Python爬取某网站数据分析报告,不满十八岁禁止观看

作者: 8f3a71b379c1 | 来源:发表于2019-06-22 14:06 被阅读216次

    声明:此文并不是标题党,如果你不满18岁,请马上关闭,在父母陪同下观看也不行。
    本文的数据抓取自国内最大的亚文化视频社区网站(不,不是 B 站),其中用户出于各种目的会在发帖的标题中加入城市名称,于是本文抓取了前10000个帖子的标题和发帖用户 ID,由于按照最近发帖的顺序排列,所以抓取数据基本上涵盖了2016年期间的发帖内容。然后通过匹配提取标题中所包含的城市信息,对16年活跃用户的归属地进行分析统计,另根据最近发布的《2016年中国主要城市 GDP 排名》:

    Python爬取某网站数据分析报告,不满十八岁禁止观看

    检验两者之间是否存在某种程度的相关。
    爬虫
    当然本文的目的主要还是出于纯粹的技术讨论与实践,数据抓取和分析处理均使用 Python 完成,其中主要用到的数据处理和可视化工具包分别是Pandas和Plot.ly+Pandas。
    由于网站使用较传统的论坛框架,经测试也没有防爬虫的措施,因此可以大胆地使用多线程,对于网页内容分析也可以直接用正则匹配完成:
    <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">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("{}|{}
    ".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()
    </pre>
    以上就是爬虫部分的代码(当然隐去了最关键的网址信息,当然这对老司机们来说并不是问题)。

    Pandas

    Pandas 可以看做是在 Python 中用于存储、处理数据的 Excel,与 R 语言中的 data.frame 的概念相似。首先将所有单独存储的文件中的数据导入到 Pandas:
    <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">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)
    </pre>
    接下来以同样的方式将国内主要城市数据、2016主要城市 GDP 排行数据加载到 Pandas 中备用。

    数据分析

    首先需要明确以目前的数据可以探讨哪些有趣的问题:

    各个城市的发帖总数;
    各个城市的活跃用户数量;
    以上两个数据结果与 GDP 之间的关系;
    发帖形式分类(虽然这个问题的答案可能更有趣,以目前的数据量很难回答这问题,而且需要涉及到较复杂的 NLP,先写在这里);
    最活跃的用户来自哪里。

    首先加载备用的数据:
    <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">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")
    </pre>
    匹配标题中是否存在城市的名称:
    <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># 先替换可能出现的“昵称”
    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)
    </pre>
    现在已经可以直接回答第一个问题了,用 Plot.ly 将 Pandas 中的数据可视化出来,有两种方式,我们选择较简单的 cufflinks 库,直接在 DataFrame 中绘制:
    <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">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))
    </pre>

    Python爬取某网站数据分析报告,不满十八岁禁止观看

    前6名基本上不出什么意外,但是大山东排在第7名,这就有点意思了。为了排除某些“特别活跃”用户的干扰,将用户重复发帖的情况去除,只看发帖用户数量:
    <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># 去除 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))
    </pre>

    Python爬取某网站数据分析报告,不满十八岁禁止观看

    Impressive,山东。至少说明还是比较含蓄,不太愿意写明具体的城市?是这样吗,这个问题可以在最后一个问题的答案中找到一些端倪。
    接下来要和 GDP 数据整合到一起,相当于将两个 DataFrame 以城市名为键 join 起来:
    <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">posts_with_city_by_user_and_gdp = posts_with_city_by_user.merge(TABLE_GDP, left_on='city', right_on='city', how='inner')
    </pre>

    Python爬取某网站数据分析报告,不满十八岁禁止观看

    由于有些漏掉的排行数据,同时由于人口数据较大,需要进行一定的预处理和标准化处理:
    <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">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
    </pre>
    绘制气泡图,气泡大小为用户数量与人口数的比,坐标值越大排行越高:


    Python爬取某网站数据分析报告,不满十八岁禁止观看

    可以看到基本上存在一定程度的相关,但是到这里我们发现更有趣的数据应该是那些出现在 GDP 排行榜上却没有出现在网站排行上的城市,是不是说明这些城市更加勤劳质朴,心无旁骛地撸起袖子干呢?
    <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">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']]
    </pre>

    Python爬取某网站数据分析报告,不满十八岁禁止观看

    注:由于 posts_with_city_by_user 只截取了前15,实际上青岛是排在前20的,从下一个结果中就能看出来…
    最后一个问题,最活跃的老司机们都来自哪个城市?
    <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">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'])
    </pre>

    Python爬取某网站数据分析报告,不满十八岁禁止观看

    总结
    以上就是全部数据与分析的结果。其实大部分只是一个直观的结果展示,既没有严谨的统计分析,也没有过度引申的解读。只有经过统计检验才能得出拥有可信度的结论,在一开始已经说明了本文只是纯粹的技术讨论与实践,所抓取的10000多条数据也只是网站中某个板块,因此对于以上结果不必太过认真。

    相关文章

      网友评论

        本文标题:Python爬取某网站数据分析报告,不满十八岁禁止观看

        本文链接:https://www.haomeiwen.com/subject/shamqctx.html