Python学习的第4天

使用爬虫提取当当网信息

import requests
from lxml import html
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def spider_dangdang(isbn):
    book_list = []
    # 目标站点地址
    url = 'http://search.dangdang.com/?key={}&act=input'.format(isbn)
    # print(url)
    # 获取站点str类型的响应
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"}

    resp = requests.get(url, headers=headers)
    html_data = resp.text
    #  将html页面写入本地
    # with open('dangdang.html', 'w', encoding='utf-8') as f:
    #     f.write(html_data)
  • 提取目标站的信息
    selector = html.fromstring(html_data)
    ul_list = selector.xpath('//div[@id="search_nature_rg"]/ul/li')
    print('您好,共有{}家店铺售卖此图书'.format(len(ul_list)))

    # 遍历 ul_list
    for li in ul_list:
        #  图书名称
        title = li.xpath('./a/@title')[0].strip()
        # print(title)
        #  图书购买链接
        link = li.xpath('a/@href')[0]
        # print(link)
        #  图书价格
        price = li.xpath('./p[@class="price"]/span[@class="search_now_price"]/text()')[0]
        price = float(price.replace('¥',''))
        # print(price)
        # 图书卖家名称
        store = li.xpath('./p[@class="search_shangjia"]/a/text()')
        # if len(store) == 0:
        #     store = '当当自营'
        # else:
        #     store = store[0]
        store = '当当自营' if len(store) == 0 else store[0]
        # print(store)

        # 添加每一个商家的图书信息
        book_list.append({
            'title':title,
            'price':price,
            'link':link,
            'store':store
        })
  • 按照价格进行排序
    book_list.sort(key=lambda x:x['price'])

    # 遍历booklist
    for book in book_list:
        print(book)
  • 展示价格最低的前10家 柱状图
    # 店铺的名称
    top10_store = [book_list[i] for i in range(10)]
    # x = []
    # for store in top10_store:
    #     x.append(store['store'])
    x = [x['store'] for x in top10_store]
    print(x)
    # 图书的价格
    y = [x['price'] for x in top10_store]
    print(y)
    # plt.bar(x, y)
    plt.barh(x, y)
    plt.show()
  • 存储成csv文件
    df = pd.DataFrame(book_list)
    df.to_csv('dangdang.csv')

spider_dangdang('9787115428028')
Python学习的第4天_第1张图片

练习-爬虫豆瓣

  • 电影名,上映日期,类型,上映国家,想看人数
  • 根据想看人数进行排序
  • 绘制即将上映电影国家的占比图
  • 绘制top5最想看的电影
import  requests
from  lxml import html
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
url='https://movie.douban.com/cinema/later/chongqing/'

resp = requests.get(url)
#获取站点str类型的
html_data=resp.text
# 提取目标站点的信息
selector = html.fromstring(html_data)
movie_info=selector.xpath('//div[@id="showing-soon"]/div')
#print(html_data)
print('你好,共有{}电影即将上映'.format(len(movie_info)))
movie_info_list=[]
for movie in movie_info:
    #电影名
    movie_name=movie.xpath('./div/h3/a/text()')[0]
    # print(movie_name)
    #上映日期
    movie_date=movie.xpath('./div/ul/li[1]/text()')[0]
    # print(movie_date)
    #电影类型
    movie_type=movie.xpath('./div/ul/li[2]/text()')[0]
    movie_type=str(movie_type)
    movie_type=movie_type.split(' / ')
    # print(type(movie_type))
    #print(movie_type)

    #上映国家
    movie_nation=movie.xpath('./div/ul/li[3]/text()')[0]
    # print(movie_nation)

    #想看人数
    movie_want = movie.xpath('./div/ul/li[4]/span/text()')[0]
    movie_want=int(movie_want.replace('人想看',''))
    # print(movie_want)

    #添加信息到列表
    movie_info_list.append({
        'name':movie_name,
        'date':movie_date,
        'type':movie_type,
        'nation':movie_nation,
        'want':movie_want
    })

#根据想看人数进行排序
movie_info_list.sort(key=lambda x : x['want'],reverse=True)
counts={}
# 绘制即将上映电影国家的占比图(饼图)
#计算上映国家的电影片数
for nation in movie_info_list:
    counts[nation['nation']] = counts.get(nation['nation'], 0) + 1
#将字典转换为列表
items = list(counts.items())
print(items)
# 取出绘制饼图的数据和标签
co=[]
lables=[]
for i in range(len(items)):
    role, count = items[i]
    co.append(count)
    lables.append(role)

explode = [0.1, 0, 0, 0]
plt.pie(co, shadow=True,explode=explode, labels=lables, autopct = '%1.1f%%')
plt.legend(loc=2)
plt.axis('equal')
plt.show()
#绘制top5最想看的电影(柱状图)

#电影名称
x = [movie_info_list[i]['name'] for i in range(5)]

# top5 = [movie_info_list[i] for i in range(5)]
# x = [x['name'] for x in top5]
#想看人数
y = [movie_info_list[i]['want'] for i in range(5)]
# y = [y['want'] for y in top5]


print(x)
print(y)
plt.xlabel('电影名称')
plt.ylabel('想看人数(人)')

plt.bar(x, y)
plt.show()
Python学习的第4天_第2张图片
饼图
Python学习的第4天_第3张图片
柱状图

你可能感兴趣的:(Python学习的第4天)