python学习 - day4

1、爬虫

  • 大数据

1-1、 提取本地html中的数据

1、新建html文件
2、读取
3、使用xpath语法进行提取
4、使用 lxml 中的xpath

  • 使用lxml提h1标签中的内容
# 先创建一个index.html



    
    Title


欢迎来到王者荣耀

  1. 坦克
  2. 战士
  3. 刺客
<
  • 结点选择语法
    XPath使用路径表达式来选取XML文档中的节点或者节点集。这些路径表达式和我们在常规的电脑文件系统中看到的表达式非常相似。
    1、 nodename:选取此节点的所有子节点;
    2、 /:从根节点选取;
    3、 //:从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置;
    4、 . :选取当前节点;
    5、 .. :选取当前节点的父节点;
    6、 @:选取属性。
- 提取本地html中的数据
from lxml import html
# 读取index.html文件
with open('./index.html', 'r', encoding='utf-8') as f:
    html_data = f.read()
    # print(html_data)
    # 解析html文件,获得selector对象
    selector = html.fromstring(html_data)
    # selecor中调用xpath方法
    # 要获取标签中的内容,末尾要添加text()
    h1 = selector.xpath('/html/body/h1/text()')
    print(h1[0])

    # // 可以代表从任意位置出发
    # // 标签1[@属性=属性值]/标签2[@属性=属性值].../text()
    a = selector.xpath('//div[@id="container"]/a/text()')
    print(a)
    # 获取 p标签的内容
    p = selector.xpath('//div[@id="container"]/p/text()')
    print(p)

    # 获取属性
    link = selector.xpath('//div[@id="container"]/a/@href')
    print(link[0])

结果:
读取本地html文件

1-2、requests

# 导入
import requests
url = 'https://www.baidu.com'
# url = 'https://www.taobao.com'
# url = 'https://www.jd.com'
# url = 'http://www.dangdang.com'
# url = 'https://www.zhihu.com'
response = requests.get(url)
print(response)
# 获取str类型的响应
print(response.text)
# 获取bytes类型的响应
print(response.content)
# 获取响应头
print(response.headers)
# 获取状态码
print(response.status_code)
# 获取编码方式
print(response.encoding)

结果:显示响应请求网站的各种状态
requests结果
  • 请求没有添加请求头的知乎网站
# 没有添加请求头的知乎网站
resp = requests.get('https://www.zhihu.com/')
print(resp.status_code)

结果:请求不成功
请求不成功
  • 复制网站的请求头

    打开知乎网站,单击鼠标右键,选择审查元素,点击如图 1-2-1 所示:
    1-2-1
  • 添加请求头后请求知乎网站
# 使用字典定义请求头
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('https://www.zhihu.com/', headers=headers)
print(resp.status_code)

结果:请求成功
结果

2、获取当当网站指定图书的商家信息

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'])
    # 遍历book_list
    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')

结果:
柱状图

3、获取豆瓣网站重庆地区即将上映的电影信息

  • 电影名,上映日期,类型,上映国家,想看人数
  • 根据想看人数进行排序
  • 绘制即将上映电影想看人数占比图和即将上映电影国家的占比图
  • 绘制top5最想看的电影
import requests
import jieba
from lxml import html
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def spider_douban():
    movie_list = []
    # 目标站点地址
    url = 'https://movie.douban.com/cinema/later/chongqing/'
    # 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

    # 提取目标站的信息
    selector = html.fromstring(html_data)
    div_list = selector.xpath('//div[@class="bd"]/div[@id="showing-soon"]/div')
    print('您好,共有{}部即将上映的电影'.format(len(div_list)))
    # 遍历ul_list
    for div in div_list:
        # 电影名称
        title = div.xpath('./div/h3/a/text()')[0]
        print(title)

        # 上映日期
        shangying_date = div.xpath('./div/ul/li/text()')[0]
        print(shangying_date)

        # 电影类型
        movie_type = div.xpath('./div/ul/li/text()')[1].strip()
        # price = float(price.replace('¥', ''))
        print(movie_type)

        # 上映国家
        shangying_country = div.xpath('./div/ul/li/text()')[2]
        print(shangying_country)

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

        # 添加每一部电影的信息
        movie_list.append({
            'title': title,
            'shangying_date': shangying_date,
            'movie_type': movie_type,
            'shangying_country': shangying_country,
            'wanted_people': wanted_people
        })

    # # 按照想看人数进行排序
    movie_list.sort(key=lambda x: x['wanted_people'], reverse=True)
    # 遍历movie_list
    # for movie in movie_list:
    #     print(movie)
    total = [x['shangying_country'] for x in movie_list]
    text = ''.join(total)
    print(text)
    # 2.分词
    counts = {}  # counts = {'姓名':出现频率}
    excludes = {"大陆"}
    words_list = jieba.lcut(text)
    print(words_list)
    for word in words_list:
        if len(word) <= 1:
            continue
        else:
            # 更新字典中的值
            # counts[word] = 取出字典中原来键对应的值 + 1
            # counts[word] = counts[word] + 1
            # 字典.get(k)  如果字典中没有这个键 ,(返回NONE)添加一个默认值:0
            counts[word] = counts.get(word, 0) + 1
    print(counts)
    # 3.词语过滤,删除无关词,重复词
    for word in excludes:
        del counts[word]
        # 4.排序[(), ()]
        items = list(counts.items())
        print(items)

        # def sort_by_count(x):
        #     return x[1]
        # items.sort(key=sort_by_count, reverse=True)
        # 用列表解析排序
        items.sort(key=lambda x: x[1], reverse=True)
        print(items)
        counts = []  # 人物名
        labels = []  # 次数
        for i in range(len(items)):
            # 序列解包
            country, count = items[i]
            print(country, count)
            # 得出结论
            # 绘制中文词云,在WordCloud()里面设置参数
            # text = ' '.join(li)
            counts.append(count)
            if country == "中国":
                country = "中国大陆"
            labels.append(country)
        print(counts)
        print(labels)
    # 距离圆心点距离
    color = ['red', 'purple', 'blue', 'yellow']
    plt.pie(counts, shadow=True, labels=labels, autopct='%1.1f%%')
    plt.axis('equal')
    plt.legend(loc=2)
    plt.show()
    # 绘制top5最想看的电影 柱状图
    # 电影的名称
    top5_movie = [movie_list[i] for i in range(5)]
    x = [x['title'] for x in top5_movie]
    print(x)
    # 想看的人数
    y = [x['wanted_people'] for x in top5_movie]
    print(y)
    # plt.bar(x, y)
    plt.barh(x, y)
    plt.show()
    print(type(movie_list))
spider_douban()

结果:
想看柱状图

国家所占比饼状图

你可能感兴趣的:(python学习 - day4)