【python爬虫】猫眼电影爬取分析

  1. 启动spyder新建文件进行代码的编写
  2. urllib.request请求到网页源代码:

豆瓣电影即将上映的影片的网页的地址是:

https://movie.douban.com/coming

开始编写代码获得该网址的源代码:

def get_response(url, headers):

    """

    获取响应对象

    :param url: 请求的url

    :param headers: 请求头信息

    :return: 返回服务器的响应信息

    """

    req = urllib.request.Request(url, headers=headers)

    resp = urllib.request.urlopen(req)

    return resp.read()

 

3.分析网页结构,并提取相应字段:

 

4.通过etree库将html信息转成对象

 

5.分析网页,制定提取策略:

在网页中审查元素发现:找到数据区域,发现table class 为 coming_list,使用通过xpath解析规则,获取需求信息html.xpath('//table[@class="coming_list"]//tr')得到所有行数据。

 

 

6.遍历节点进行数据清洗,并将数据以json格式保存:

item = []

    for row in rows:

        td = row.xpath('td')

        if len(td) == 0:

            continue

        

        # 07月05日

        date = td[0].text.strip()

        # 爱宠大机密2

        name = td[1].xpath('a')[0].text.strip()

        #原始数据:喜剧 / 动画 / 冒险  清洗后数据: ['喜剧', '动画', '冒险']

        type = td[2].text.strip().split(' / ')

        #原始数据:中国大陆 / 香港     清洗后数据:['中国大陆', '香港']

        region = td[3].text.strip().split(' / ')

        #原始数据:25768人           清洗后数据:25768

        num = int(td[4].text.strip()[:-1])

       

        temp = [date,name,type,region,num]

        item.append(temp)

7.分析统计关注量并绘制横向柱状图图表:

    # 按第四列进行排序

    item.sort(reverse=True,key=takecol4)

    labels = []

    nums = []

    temp = 0

    # 关注度最高的10部电影

    for i in item:

        labels.append(i[1])

        nums.append(i[4])

        temp += 1

        if temp > 9:

            break

       

    #为实现图表更加美观进行数据翻转

    labels.reverse()

    nums.reverse()

    x = nums

    idx = np.arange(len(x))

    color = cm.jet(np.array(x)/max(x))

    plt.barh(idx, x, color=color)

    plt.yticks(idx+0.4,labels)

    plt.grid(axis='x')

   

    #设置数据标签

    for a,b in zip(idx,x):

        plt.text(b+1800,a-0.4,'%d'%int(b),ha='center',va='bottom')

   

    #添加行列标签和标题

    plt.xlabel('关注人数')

    plt.ylabel('电影名称')

    plt.title('电影关注排行榜')

    plt.show()

8.分析类别信息并绘制饼图:

types = []

    # 关注度最高的10部电影

    for i in item:

        types += i[2]

    count_dict = dict()

    for t in types:

        if t in count_dict:

            count_dict[t] += 1

        else:

            count_dict[t] = 1

    labels = count_dict.keys()

    types = count_dict.values()

   

    #color = cm.jet(np.array(types)/max(types))

    plt.pie(types, labels=labels,

             autopct='%1.1f%%', startangle=90)

    plt.axis('equal')

    plt.show()

 

详细代码见GitHub:https://github.com/ty33123/spider_learn/tree/master/maoyan

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值