python学习第四天

1.爬虫

  1. 大数据 , 提取本地hmtl中的数据
  2. 步骤
    ①新建html文件
    ②读取
    ③使用lxml中的xpath语法进行提取
from lxml import html
# 读取html文件
with open('./index.html', 'r', encoding='utf-8') as f:
    html_data = f.read()
    # selector中调用xpath方法
    selector = html.fromstring(html_data)
    # 要获取标签中的内容,末尾要添加text()
    h1 = selector.xpath('/html/body/h1/text()')
    print(h1[0])
    # //可以从任意位置出发
    # //标签1[@属性=属性值]/标签2[@属性=属性值].../text()
    a = selector.xpath('//div[@id="container"]/a/text()')
    print(a[0])
    # 获取p标签内容
    p = selector.xpath('//div[@id="container"]/p/text()')
    print(p[0])
    # 获取属性 @属性名
    link = selector.xpath('//div[@id="container"]/a/@href')
    print(link[0])
image.png

2.关于requests

# 导入
import requests
url = 'https://www.baidu.com'
# url = 'https://www.taobao.com'
# url = 'https://www.jd.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)
# 没有添加请求头的知乎网网站
# resp = requests.get('https://www.zhihu.com/')
# print(resp.status_code)
# 使用字典定义请求头
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)
image.png

3.爬当当网

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')
image.png

image.png

价格最低Top10

4.练习--爬重庆-影讯

import requests
from lxml import html
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
people_list = []
counts = []
# 目标站点地址
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)
ul_list = selector.xpath('//div[@id="showing-soon"]/div/div')
print('您好,共有{}部电影即将上映'.format(len(ul_list)))
# 遍历 ul_list
for li in ul_list:
    #  电影名称
    title = li.xpath('./h3/a/text()')[0].strip()
    # print(title)
    # 上映日期
    date = li.xpath('./ul/li/text()')[0]
    # print(date)
    #  类型
    type = li.xpath('./ul/li/text()')[1]
    # print(type)
    # 上映国家
    country = li.xpath('./ul/li/text()')[2]
    # print(country)
    # 想看人数
    people = li.xpath('./ul/li/span/text()')[0]
    people = int(people.replace('人想看', ''))
    # print(people)
    people_list.append({
        'title': title,
        'date': date,
        'type': type,
        'country': country,
        'people': people
    })
    counts.append(country)
# 按照想看人数进行排序
people_list.sort(key=lambda x:x['people'], reverse=True)
# 遍历people_list
for num in people_list:
    print(num)
# 展示想看人数top5
top5 = [people_list[i] for i in range(5)]
x = [x['title'] for x in top5]
print(x)
y = [x['people'] for x in top5]
print(y)
plt.barh(x, y)
plt.show()
# 国家占比
china = 0
japan = 0
hongkong = 0
russia = 0
for i in range(22):
    if counts[i] == '中国大陆':
        china += 1
    elif counts[i] == '日本':
        japan += 1
    elif counts[i] == '香港':
        hongkong += 1
    else:
        russia += 1
count1 = ['中国大陆', '日本', '香港', '俄罗斯']
count2 = [china, japan, hongkong, russia]
plt.pie(count2, shadow=True, labels=count1, autopct='%1.1f%%')
plt.legend(loc=2)
plt.axis('equal')
plt.show()
image.png

展示想看人数top5

电影国家占比
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,527评论 5 470
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,314评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,535评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,006评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,961评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,220评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,664评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,351评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,481评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,397评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,443评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,123评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,713评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,801评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,010评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,494评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,075评论 2 341