本篇文章是使用 python 抓取数据的第二篇,使用 urllib 方法对人人贷网站贷款列表页进行抓取。并从中获取贷款用户,金额和期限的分布情况。
首先是准备工作,导入需要使用的库文件,re 用于通过正则提取数据,time 用于设置 Sleep 时间,numpy 用于数值计算,pandas 用于数据汇总和分析,urllib 用于数据抓取,matplotlib 用于数据可视化。
- #导入所需库文件import re import time import numpy as np import pandas as pd import urllib.request import matplotlib.pyplot as plt
开始抓取前设置列表页的 URL 地址,其中 page - 后面的部分是页码,将在后面动态生成。
url='http://www.we.com/loan#page-'
设置请求的头文件信息,这部分内容可以在 Chrome 的开发者工具中获得,或者在网站搜索头文件信息。
列表页共有 52 个页面,使用 for 循环每次输出一个页码,与之前设置的 URL 地址拼接成要抓取的列表页 URL,并进行抓取。每次抓取间休息 2 秒针。将抓取的到的页面保存在 html 中。
- #循环抓取列表页信息
- for i in range(0, 52) : i = str(i) if i == 0 : req = urllib.request.Request(url = url + i, headers = headers) resq = urllib.request.urlopen(req, timeout = 2) html = resq.read()
- else: req = urllib.request.Request(url = url + i, headers = headers) resq = urllib.request.urlopen(req, timeout = 2) html2 = resq.read() html = html + html2 time.sleep(2) print(url + i)
抓取到的页面需要进行解析,然后使用正则提取关键信息,以便后续的分析过程。
- #对页面进行解析html = html.decode('utf-8')
- #使用正则提取title字段title = re.findall(r '"title":(.*?),', html)
- #使用正则提取amount字段amount = re.findall(r '"amount":(.*?),', html)#使用正则提取interest字段interest = re.findall(r '"interest":(.*?),', html)#使用正则提取months字段months = re.findall(r '"months":(.*?),', html)
将提取的字段拼接在一起创建用于分析的数据透视表。并对数据进行清洗和预处理。
- #拼接字段创建名为rrd的数据表rrd = pd.DataFrame({
- 'title': title,
- 'amount': amount,
- 'interest': interest,
- 'months': months
- })
- #查看表的维度,1020行,4列rrd.shape(1020, 4)
- #查看数据表前5行rrd.head()
- #查看字段类型rrd.dtypes amount object interest object months object title object dtype: object
- #更改amount,interest和months字段的格式rrd[['amount', 'interest', 'months']] = rrd[['amount', 'interest', 'months']].astype(np.float64)
- #再次查看更改后的字段格式rrd.dtypes amount float64 interest float64 months float64 title object dtype: object
查看数据表中的贷款数据的关键指标,如贷款总金额,总笔数,人均贷款金额和贷款金额范围等等。
- #总贷款金额和笔数rrd['amount'].sum(),
- rrd['amount'].count()(95390400.0, 1020)#平均贷款金额rrd['amount'].sum() / rrd['amount'].count() 93520.0#贷款金额的最大值和最小值rrd['amount'].max(),
- rrd['amount'].min()(262000.0, 15400.0)
贷款总金额 9539 万元,笔数 1020 笔。每一笔的平均贷款金额为 93520 元。贷款金额最大值为 262000 元,最小值为 15400 元。
按贷款目的对比贷款金额及笔数的分布情况,首先分别按贷款目的汇总贷款金额和笔数数据。
- #按贷款目的汇总贷款笔数title_count = rrd.groupby('title')['amount'].agg('count')#按贷款目的汇总贷款金额title_sum = rrd.groupby('title')['amount'].agg('sum')
绘制图表查看金额和笔数分布情况。从图表中可以看出日常生活消费的贷款笔数最多,但总金额较低,而资金周转的贷款笔数较低,但总贷款金额较大。
- #绘制贷款用户金额及笔数分布图plt.rc('font', family = 'STXihei', size = 15) a = np.array([1, 2, 3, 4, 5]) plt.figure() plt.barh([1, 2, 3, 4, 5], title_count, color = '#99CC01', alpha = 0.8, align = 'center', edgecolor = 'white') plt.barh([1, 2, 3, 4, 5], -rrd_title, color = '#39A2E1', alpha = 0.8, align = 'center', edgecolor = 'white') plt.ylabel('贷款用途分类') plt.title('贷款用户金额及笔数') plt.xticks(a, ('')) plt.yticks(a, ('资金周转', '装修', '增购新车', '购买货物', '日常生活消费')) plt.show()
贷款期限分布
按贷款期限对贷款笔数进行汇总,查看不同期限的贷款笔数分布情况。首先对数据按期限进行汇总。
- #按期限汇总贷款笔数month_count = rrd.groupby('months')['amount'].agg('count')
绘制图表,查看贷款期限分布情况,大部分贷款期限为 36 个月,24 个月和 48 个月的贷款数量明显较少。
- #汇总不同期限贷款笔数分布图plt.rc('font', family = 'STXihei', size = 15) a = np.array([1, 2, 3]) plt.bar([1, 2, 3], month_count, color = '#99CC01', alpha = 0.8, align = 'center', edgecolor = 'white') plt.xlabel('期限分布') plt.ylabel('贷款笔数') plt.title('不同期限的贷款笔数分布') plt.legend(['贷款笔数'], loc = 'best') plt.grid(color = '#95a5a6', linestyle = '--', linewidth = 1, axis = 'y', alpha = 0.4) plt.xticks(a, (['24个月', '36个月', '48个月'])) plt.show()
贷款金额分布
对贷款金额进行分组,5 万元一组,共分为 6 组。然后查看各个分组内贷款金额的情况。首先对贷款金额进行分组,然后按分组对金额进行汇总。
- #对贷款金额进行分组bins = [0, 50000, 100000, 150000, 200000, 250000, 300000] amount_group = ['0-5万', '5-10万', '10-15万', '15-20万', '20-25万', '25-30万'] rrd['amount_group'] = pd.cut(rrd['amount'], bins, labels = amount_group)
- #查看分组后的数据表rrd.head()
- #按贷款金额分组汇总笔数amount_group = rrd.groupby('amount_group')['amount_group'].agg(len)
绘制贷款用户金额分布图,从图表中可以看出,5-10 万元的贷款笔数做多,其次为 0-5 万元。大金额的贷款笔数较少。
- #绘制贷款用户金额分布图plt.rc('font', family = 'STXihei', size = 13) a = np.array([1, 2, 3, 4, 5, 6]) plt.bar([1, 2, 3, 4, 5, 6], amount_group, color = '#99CC01', alpha = 0.8, align = 'center', edgecolor = 'white') plt.xlabel('金额分组') plt.ylabel('贷款笔数') plt.title('贷款用户金额分布') plt.legend(['笔数'], loc = 'upper right') plt.grid(color = '#95a5a6', linestyle = '--', linewidth = 1, axis = 'y', alpha = 0.4) plt.xticks(a, ('0-5万', '5-10万', '10-15万', '15-20万', '20-25万', '25-30万')) plt.show()
来源: http://www.tuicool.com/articles/QZZ3uuv