python學(xué)習(xí) - day4

1、爬蟲

  • 大數(shù)據(jù)

1-1、 提取本地html中的數(shù)據(jù)

1、新建html文件
2、讀取
3、使用xpath語法進(jìn)行提取
4、使用 lxml 中的xpath

  • 使用lxml提h1標(biāo)簽中的內(nèi)容
# 先創(chuàng)建一個index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>歡迎來到王者榮耀</h1>
<ul>
    <li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/508/508.jpg" alt="">伽羅</a></li>
    <li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/510/510.jpg" alt="">孫策</a></li>
    <li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" alt="">鎧</a></li>
    <li>虞姬</li>
</ul>
<ol>
    <li>坦克</li>
    <li>戰(zhàn)士</li>
    <li>刺客</li>
</ol>
<!--div + css 布局-->
<div id="container">
    <p>被動:</p>
    <a >點(diǎn)擊跳轉(zhuǎn)至百度</a>
</div>
<
</body>
</html>
  • 結(jié)點(diǎn)選擇語法
    XPath使用路徑表達(dá)式來選取XML文檔中的節(jié)點(diǎn)或者節(jié)點(diǎn)集。這些路徑表達(dá)式和我們在常規(guī)的電腦文件系統(tǒng)中看到的表達(dá)式非常相似。
    1、 nodename:選取此節(jié)點(diǎn)的所有子節(jié)點(diǎn);
    2、 /:從根節(jié)點(diǎn)選??;
    3、 //:從匹配選擇的當(dāng)前節(jié)點(diǎn)選擇文檔中的節(jié)點(diǎn),而不考慮它們的位置;
    4、 . :選取當(dāng)前節(jié)點(diǎn);
    5、 .. :選取當(dāng)前節(jié)點(diǎn)的父節(jié)點(diǎn);
    6、 @:選取屬性。
- 提取本地html中的數(shù)據(jù)
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中調(diào)用xpath方法
    # 要獲取標(biāo)簽中的內(nèi)容,末尾要添加text()
    h1 = selector.xpath('/html/body/h1/text()')
    print(h1[0])

    # // 可以代表從任意位置出發(fā)
    # // 標(biāo)簽1[@屬性=屬性值]/標(biāo)簽2[@屬性=屬性值].../text()
    a = selector.xpath('//div[@id="container"]/a/text()')
    print(a)
    # 獲取 p標(biāo)簽的內(nèi)容
    p = selector.xpath('//div[@id="container"]/p/text()')
    print(p)

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

結(jié)果:
讀取本地html文件

1-2、requests

# 導(dǎo)入
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類型的響應(yīng)
print(response.text)
# 獲取bytes類型的響應(yīng)
print(response.content)
# 獲取響應(yīng)頭
print(response.headers)
# 獲取狀態(tài)碼
print(response.status_code)
# 獲取編碼方式
print(response.encoding)

結(jié)果:顯示響應(yīng)請求網(wǎng)站的各種狀態(tài)
requests結(jié)果
  • 請求沒有添加請求頭的知乎網(wǎng)站
# 沒有添加請求頭的知乎網(wǎng)站
resp = requests.get('https://www.zhihu.com/')
print(resp.status_code)

結(jié)果:請求不成功
請求不成功
  • 復(fù)制網(wǎng)站的請求頭

    打開知乎網(wǎng)站,單擊鼠標(biāo)右鍵,選擇審查元素,點(diǎn)擊如圖 1-2-1 所示:
    1-2-1
  • 添加請求頭后請求知乎網(wǎng)站
# 使用字典定義請求頭
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)

結(jié)果:請求成功
結(jié)果

2、獲取當(dāng)當(dāng)網(wǎng)站指定圖書的商家信息

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 = []
    # 目標(biāo)站點(diǎn)地址
    url = 'http://search.dangdang.com/?key={}&act=input'.format(isbn)
    # print(url)
    # 獲取站點(diǎn)str類型的響應(yīng)
    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)

    # 提取目標(biāo)站的信息
    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)

        # 圖書價(jià)格
        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 = '當(dāng)當(dāng)自營'
        # else:
        #     store = store[0]
        store = '當(dāng)當(dāng)自營' if len(store) == 0 else store[0]
        # print(store)

        # 添加每一個商家的圖書信息
        book_list.append({
            'title': title,
            'price': price,
            'link': link,
            'store': store
        })

    # 按照價(jià)格進(jìn)行排序
    book_list.sort(key=lambda x: x['price'])
    # 遍歷book_list
    for book in book_list:
        print(book)

    # 展示價(jià)格最低的前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)
    # 圖書的價(jià)格
    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')

結(jié)果:
柱狀圖

3、獲取豆瓣網(wǎng)站重慶地區(qū)即將上映的電影信息

  • 電影名,上映日期,類型,上映國家,想看人數(shù)
  • 根據(jù)想看人數(shù)進(jìn)行排序
  • 繪制即將上映電影想看人數(shù)占比圖和即將上映電影國家的占比圖
  • 繪制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 = []
    # 目標(biāo)站點(diǎn)地址
    url = 'https://movie.douban.com/cinema/later/chongqing/'
    # print(url)
    # 獲取站點(diǎn)str類型的響應(yīng)
    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

    # 提取目標(biāo)站的信息
    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)

        # 想看人數(shù)
        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
        })

    # # 按照想看人數(shù)進(jìn)行排序
    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 = {'姓名':出現(xiàn)頻率}
    excludes = {"大陸"}
    words_list = jieba.lcut(text)
    print(words_list)
    for word in words_list:
        if len(word) <= 1:
            continue
        else:
            # 更新字典中的值
            # counts[word] = 取出字典中原來鍵對應(yīng)的值 + 1
            # counts[word] = counts[word] + 1
            # 字典.get(k)  如果字典中沒有這個鍵 ,(返回NONE)添加一個默認(rèn)值:0
            counts[word] = counts.get(word, 0) + 1
    print(counts)
    # 3.詞語過濾,刪除無關(guān)詞,重復(fù)詞
    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 = []  # 次數(shù)
        for i in range(len(items)):
            # 序列解包
            country, count = items[i]
            print(country, count)
            # 得出結(jié)論
            # 繪制中文詞云,在WordCloud()里面設(shè)置參數(shù)
            # text = ' '.join(li)
            counts.append(count)
            if country == "中國":
                country = "中國大陸"
            labels.append(country)
        print(counts)
        print(labels)
    # 距離圓心點(diǎn)距離
    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)
    # 想看的人數(shù)
    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()

結(jié)果:
想看柱狀圖

國家所占比餅狀圖
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容