python學習的第四天

谷歌瀏覽器安裝插件XPath Helper

運行界面

XPath Helper運行.png

爬蟲

from lxml import html
with open('./index.html', 'r', encoding='utf-8') as f:
    html_test = f.read()
    select = html.fromstring(html_test)
    h1 = select.xpath('/html/body/h1/text()')
    print(h1[0])

    a= select.xpath('//div[@id="container"]/p/text()')
    print(a[0])
爬蟲入門.png

爬蟲--當當網(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 = []
    # 目標站點地址
    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')

當當網(wǎng)圖書.png

豆瓣

#電影名,上映日期,類型,上映國家,想看人數(shù)
#根據(jù)想看人數(shù)進行排序
#繪制即將上映電影國家的占比圖
#繪制top5最想看的電影

import requests
from lxml import html
from wordcloud import WordCloud
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def spider_movie():
    movie_list = []
    url = 'https://movie.douban.com/cinema/later/chongqing/'
    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[@id="showing-soon"]/div')
    print('共有{}部電影即將上映'.format(len(div_list)))

    for div in div_list:
        # 電影名
        move_name = div.xpath('./div[@class="intro"]/h3/a/text()')[0]
        # print(name)

        # 上映日期
        move_day = div.xpath('./div[@class="intro"]/ul/li/text()')[0]
        # print(day)

        # 類型
        move_type = div.xpath('./div[@class="intro"]/ul/li/text()')[1]
        # print(type)

        # 上映國家
        move_country = div.xpath('./div[@class="intro"]/ul/li/text()')[2]
        # print(country)

        # 想看人數(shù)
        div_three = div.xpath('./div[@class="intro"]/ul/li')[3]
        number = div_three.xpath('./span/text()')[0]
        number = str(number).replace('人想看', '')
        number = int(number)
        # print(number)

        # 添加電影信息
        movie_list.append({
            'name':move_name,
            'day':move_day,
            'type':move_type,
            'country':move_country,
            'number':number
        })

    # 排序
    movie_list.sort(key=lambda x:x['number'], reverse=True)

    # 遍歷
    for movie in movie_list:
        print(movie)

    # 繪制即將上映電影最想看前五人數(shù)占比圖
    top5_movie = [movie_list[i] for i in range(4)]
    labels = [x['name'] for x in top5_movie]
    # print(labels)
    counts = [x['number'] for x in top5_movie]
    # print(counts)
    colors = ['red', 'purple', 'yellow', 'gray', 'green']
    plt.pie(counts, labels=labels, autopct='%1.2f%%', colors=colors)
    plt.legend(loc=2)
    plt.axis('equal')
    plt.show()

     # 繪制即將上映電影國家的占比圖
    total = [x['country'] for x in movie_list]
    text = ''.join(total)
    print(text)
    words_list = jieba.lcut(text)
    print(words_list)
    counts = {}
    excludes ={"大陸"}
    for word in words_list:
        if len(word) <= 1:
            continue
        else:
            counts[word] = counts.get(word, 0) + 1
    print(counts)
    for word in excludes:
        del counts[word]
    items = list(counts.items())
    print(items)
    items.sort(key=lambda x: x[1], reverse=True)
    print(items)
    numm = [] # 數(shù)量
    labels = [] # 國家
    for i in range(len(items)):
        x, y = items[i]
        numm.append(y)
        if(x == "中國"):
            x = "中國大陸"
        labels.append(x)
    plt.pie(numm, labels=labels, autopct='%1.2f%%')
    plt.legend(loc=2)
    plt.axis('equal')
    plt.show()

    # top5.png
    text = ' '.join(labels)
    WordCloud(
        font_path='MSYH.TTC',
        background_color='white',
        width=800,
        height=600,
        collocations=False
    ).generate(text).to_file('top5.png')

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

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

  • 爬蟲——大數(shù)據(jù) 1. 提取本地HTML中的數(shù)據(jù) 1. 新建index.html文件 2. 讀取HTML文件 需要安...
    婉兒吖閱讀 409評論 0 0
  • 1、爬蟲一些知識 (1)節(jié)點選擇語法 XPath使用路徑表達式來選取XML文檔中的節(jié)點或者節(jié)點集。這些路徑表達式和...
    小烏龜快點跑吖閱讀 369評論 0 0
  • 一、爬蟲 1.本地提取 ①.新建html文件 界面如下: ②.讀?、?使用xpath語法進行提取使用lxml提取h...
    唐旭濤閱讀 339評論 0 0
  • 爬蟲 在Gogle瀏覽器上安裝Xpath Helper插件 實例:爬圖書的價格,排序等 作業(yè):爬電影網(wǎng)站,得到電影...
    佑印無心閱讀 187評論 0 0
  • 香港Lp54谷紅梅,我是一個自信、美麗、堅強的女人。今天我要以真誠、自信、付出的心態(tài)創(chuàng)造一個高效、有結果的星期六 ...
    谷紅梅閱讀 105評論 0 0

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