Python學(xué)習(xí)的第四天

一、提取網(wǎng)頁中數(shù)據(jù)

#爬蟲
#大數(shù)據(jù)
#提取本地html文件
#使用xpath語法進行提取
#使用lxml中的xpath
#使用lxml提取h1中的內(nèi)容
from lxml import html #若報錯找不到指定的模塊,就卸載掉然后再安裝
#提取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)
    #selector中調(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[@屬性=屬性值]container
    a=selector.xpath('//div[@class="container"]/a/text()')
    print(a[0])
    p=selector.xpath('//div[@class="container"]/p/text()')
    print(p[0])

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

二、獲取響應(yīng)

#導(dǎo)入
import requests
url='https://www.baidu.com'
response=requests.get(url)
print(response)
#獲取str類型的響應(yīng)
#response常用
print(response.text)
#獲取bytes類型的響應(yīng),下載圖片用到
print(response.content)
#獲取響應(yīng)頭,
print(response.headers)
#獲取狀態(tài)碼:200 404 500
print(response.status_code)
#獲取編碼
print(response.encoding)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>王者榮耀</title>
</head>
<body>

<h1>歡迎來到王者榮耀</h1>
<ul>
    <li><a  ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/508/508.jpg"> 伽羅</a></li>
    <li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/174/174.jpg"> 虞姬</a> </li>
    <li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/135/135.jpg" > 項羽</a></li>
    <li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/109/109.jpg"> 妲己</a> </li>

</ul>
<ol>
    <li>坦克</li>
    <li>法師</li>
    <li>射手</li>
    <li>刺客</li>
</ol>
<div>這是div標(biāo)簽</div>
<div class="container">
    <p>被動:伽羅的普工與技能傷害將會有限對于表的護盾效果造成一次等額傷害</p>
    <a >點擊跳轉(zhuǎn)</a>
</div>
<div>這是第二個div標(biāo)簽</div>
</body>
</html>

三、對當(dāng)當(dāng)網(wǎng)爬蟲數(shù)據(jù)

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):
    booklist=[]
    #目標(biāo)站點地址
    url='http://search.dangdang.com/?key={}&act=input'.format(isbn)
    #print(url)
    #獲取站點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)
        #圖書價格
        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)

        #添加每一個商家信息
        booklist.append({
            'title':title,
            'price':price,
            'link':link,
            'store':store
        })
        #按照價格進行排序
    booklist.sort(key=lambda x:x['price'],reverse=True)
        #遍歷booklist
    for book in booklist:
        print(book)
        #展示價格最低的前10家  柱狀圖
        #店鋪名稱
    top10_store=[booklist[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.barh(x,y)
    plt.show()
        #存儲為CSV文件
    df=pd.DataFrame(booklist)
    df.to_csv('dangdang.csv')
spider_dangdang('9787115428028')

四、練習(xí):對豆瓣網(wǎng)爬蟲

#練習(xí):https://movie.douban.com/cinema/later/chongqing/
#電影名,上映日期,類型,上映國家,想看人數(shù)
#根據(jù)想看人數(shù)進行排序
#繪制即將上映電影國家的占比圖
#繪制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

counts={}
# 目標(biāo)站點地址
def spider_douban():
    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

#  將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="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)
        # 想看人數(shù)
        num = li.xpath('./ul/li/span/text()')[0]
        print(num)
        num = int(num.replace('人想看', ''))

        #添加電影信息
        movie_list.append({
            'title':title,
            'date': date,
            'type':type,
            'country':country,
            'num':num
        })

    #按照人數(shù)進行排序
    movie_list.sort(key=lambda x:x['num'],reverse=True)

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

    #畫餅圖,把國家提取出來
    city=[]
    # 提取國家信息
    for country in movie_list:
        city.append((country['country']))

    # 將國家信息匯總
    for country in city:
        if len(country) <= 1:
            continue
        else:
            counts[country] = counts.get(country, 0) + 1
    items = list(counts.items())
    print(items)

    movie_name=[]
    people=[]
    for i in range(4):
        role, count = items[i]
        print(role, count)
        movie_name.append(role)
        people.append(count)


     #繪制即將上映電影國家的占比圖,餅圖

    explode = [0.1, 0, 0, 0]
    plt.pie(people, explode=explode,labels=movie_name, shadow=True, autopct='%1.1f%%')
    plt.axis('equal')  # 保證餅狀圖是正圓,否則會有點扁
    plt.show()


    # 展示最想看的前5家,柱狀圖
    # 電影名稱
    top5_movie = [movie_list[i] for i in range(5)]
    print(top5_movie)
    x = [x['title'] for x in top5_movie]
    print(x)
    # 想看人數(shù)
    y = [x['num'] for x in top5_movie]
    print(y)

    plt.bar(x,y)
    #plt.barh(x,y)
    plt.show()
    存儲成csv文件
    df = pd.DataFrame(movie_list)
    df.to_csv('douban.csv')

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

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

  • 爬蟲 爬蟲(又被稱為網(wǎng)頁蜘蛛,網(wǎng)絡(luò)機器人),它是一種按照一定的規(guī)則,自動地抓取互聯(lián)網(wǎng)信息的程序或者腳本。也即它是一...
    小頴子閱讀 242評論 0 0
  • 1.爬蟲基礎(chǔ) 1.1獲取網(wǎng)址 url='https://www.baidu.com'response=reques...
    神坑少女7閱讀 197評論 0 0
  • 一、爬蟲 爬蟲(又被稱為網(wǎng)頁蜘蛛,網(wǎng)絡(luò)機器人),它是一種按照一定的規(guī)則,自動地抓取互聯(lián)網(wǎng)信息的程序或者腳本。也即它...
    喵青禾閱讀 418評論 0 0
  • 1、爬蟲一些知識 (1)節(jié)點選擇語法 XPath使用路徑表達式來選取XML文檔中的節(jié)點或者節(jié)點集。這些路徑表達式和...
    小烏龜快點跑吖閱讀 365評論 0 0
  • 用腦學(xué)習(xí)知識,知識學(xué)習(xí)越多,技能提升的概率越大。當(dāng)知識和技能都在不斷提升的時時候,人會更用心去學(xué)習(xí)。把知識學(xué)以致用...
    FineYoGa瑜伽仙仙閱讀 180評論 0 0

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