一、主題式網絡爬蟲設計方案
1,主題式網絡爬蟲名稱:
爬取愛奇藝影片熱榜
2,主題式網絡爬蟲爬取的內容與數據特征分析:
爬取內容為:影片名稱,排名,與其點擊量
數據特征分析:將其儲存於csv或xlsx文件中
3.主題式網絡爬蟲設計方案概述(包括實現思路與技術難點)
實現思路:首先進行對網頁源代碼的訪問分析,用BeautifulSoup進行HTML的解析和信息的爬取,后續對爬取下來的信息用pandas進行繪圖數據分析
技術難點:爬取信息時對標簽的查找,寫出查找所需標簽的代碼,對數據進行相應的分析
二、主題頁面的結構特征分析
打開網址http://v.iqiyi.com/index/dianying/index.html,F12或右鍵點擊檢查
源代碼中可以看到,影片標題的名稱在div標簽下的a,title-link標簽中,點擊數在標簽div,qy-top-title-zhishu中
用for語句及find_all語句進行遍歷和爬取
三、網絡爬蟲程序設計
#導入所需要的BeautifulSoup和pandas
import requests import pandas as pd
from bs4 import BeautifulSoup #待爬取的網址 url = "http://v.iqiyi.com/index/dianying/index.html" #模擬瀏覽器 header={"User-Agent": "kaidie"} #發送請求 r = requests.get(url,headers=header) #創建標題的空列表 titlelist=[] #創建點擊數的空列表 mathlist=[] #為儲存數據創立空列表 alist=[] #用BeautifulSoup進行html的解析
html = r.text soup=BeautifulSoup(html,'html.parser') #找到所對應的標簽 #用for遍歷循環find_all查找語句查找標題 for a in soup.find_all("a","title-link"): titlelist.append(a.string) #同理找視頻的點擊數 for div in soup.find_all("div","qy-top-title-zhishu"): mathlist.append(div.string)
print("-------------------------愛奇藝影片榜前25-------------------------") print("{:^10}\t{:^30}\t{:^20}".format("排名","電影名","點擊數")) #獲取愛奇藝影片榜前25名 for i in range(25): print("{:^10}\t{:^30}\t{:^20}".format(i+1,titlelist[i],mathlist[i])) #將獲取的數據放入alist的空列表中 for i in range(25): alist.append([i+1,titlelist[i],mathlist[i]]) #用pandas對數據進行儲存,做到數據的持久化
A = pd.DataFrame(alist,columns = ['排名','電影名','點擊數']) A.to_excel('愛奇藝排行.xlsx')
2.對數據進行清洗和處理
#讀取文件中的信息 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) #打印出所有的信息 df.head(25)
#根據具體的需求可以清除不需要的數據 df.drop("點擊數", axis=1,inplace=True) df.head(10)
#重復值的處理 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) df.duplicated()
#異常值的觀察 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) df.describe()
#查看相關系數 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) df.corr()
3.文本分析
#首先導入做詞雲所需要的 from wordcloud import WordCloud import matplotlib.pyplot as plt from imageio import imread
#讀取愛奇藝排行.xlsx將其中的電影名寫到txt文本中去 Name = pd.read_excel("愛奇藝排行.xlsx", encoding='utf-8') with open("電影名.txt",'a+', encoding='utf-8') as f: for title in Name.電影名: f.write((str(title)+'\n')) #讀取電影名.txt文本 text=open('電影名.txt',encoding='utf-8').read() #詞雲的背景圖片 photo=imread('手牽手.jpg') Cyun=WordCloud( background_color = "white", mask = photo, width=1600, repeat=True, font_path=r'simfang.ttf', height=1600).generate(text) plt.imshow(Cyun) plt.axis("off") plt.show() #保存詞雲圖片 Cyun.to_file("愛奇藝詞雲.jpg")
生成的詞雲如下
4.數據分析與可視化
#根據畫圖的需求導入相應的庫 from matplotlib import pyplot as plt import numpy as np import matplotlib.pyplot as plt import matplotlib
import seaborn as sns
#定義一個散點圖的函數
#排名與點擊數的散點圖 def Sspot(): df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) #賦予x,y所對應的值 x = df.排名 y = df.點擊數 plt.xlabel("排名") plt.ylabel("點擊數") plt.scatter(x,y,color="green",label="散點") plt.title("排名與點擊數的散點圖") plt.legend() plt.show() Sspot()
#繪制扇形圖 def Pspot(): df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) x = df.電影名 y = df.點擊數 #前五名的電影標題 name = [x[0],x[1],x[2],x[3],x[4]] math = [y[0],y[1],y[2],y[3],y[4]] explode=[0.1,0.1,0.1,0.1,0.1] plt.pie(math,labels=name,colors=["r","g","c","b","y"],explode=explode) plt.axis("equal") plt.title("點擊數與電影的扇形圖") plt.show() Pspot()
#排名與點擊數的條形圖 def Tspot(): df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) x = df.排名 y = df.點擊數 plt.xlabel("排名") plt.ylabel("點擊數") plt.bar(x,y,color="green") plt.title("排名與點擊數的條形圖") plt.show() Tspot()
#前五名的電影與點擊數的條形圖 def Tspot2(): df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) x = df.電影名[:5] y = df.點擊數[:5] plt.xlabel("電影名") plt.ylabel("點擊數") plt.bar(x,y,color="green") plt.title("電影名與點擊數的條形圖") plt.show() Tspot2()
#排名與點擊數的折線圖 def Zspot(): df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) x = df.排名 y = df.點擊數 plt.xlabel("排名") plt.ylabel("點擊數") plt.plot(x,y,color="green",label="折線") plt.title("排名與點擊數的折線圖") plt.legend() plt.show() Zspot()
#回歸直線的圖 def huigui(): #x,y為回歸直線的排名和點擊數 x = df.排名 y = df.點擊數 #X,Y為散點圖的 X = df.排名 Y = df.點擊數 #先定義所需要的數據 x_i2=0 x_i =0 y_i=0 #計算出x,y的均值用mean() q = x.mean() w = y.mean() for i in range(25): x_i2 = x_i+x[i]*x[i] x_i = x_i+x[i] y_i = y_i+y[i] #運用回歸直線的公式計算出所需要的值 #分子 m_1 = x_i*y_i-25*q*w #分母 m_2 = x_i2-25*q*q #斜率 k = m_1/m_2 #截距 b = w-q*k x=np.linspace(0,25) y=k*x+b print("斜率k=",k,"截距b=",b) plt.figure(figsize=(6,4)) plt.xlabel('排名') plt.ylabel('點擊數') plt.scatter(X,Y,color="green",label="散點",linewidth=2) plt.plot(x, y,color="blue",label= "回歸直線") plt.title("回歸直線圖") plt.legend() plt.show() huigui()
#排名和點擊數的線性關系 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) sns.lmplot(x="排名",y= "點擊數",data=df)
5.完整程序代碼
1 #導入所需要的BeautifulSoup和pandas 2 import requests 3 import pandas as pd 4 from bs4 import BeautifulSoup 5 #根據畫圖的需求導入相應的庫 6 from matplotlib import pyplot as plt 7 import numpy as np 8 import matplotlib.pyplot as plt 9 import matplotlib 10 import seaborn as sns 11 #導入做詞雲所需要的 12 from wordcloud import WordCloud 13 import matplotlib.pyplot as plt 14 from imageio import imread 15 16 #待爬取的網址 17 url = "http://v.iqiyi.com/index/dianying/index.html" 18 #模擬瀏覽器 19 header={"User-Agent": "kaidie"} 20 #發送請求 21 r = requests.get(url,headers=header) 22 #創建標題的空列表 23 titlelist=[] 24 #創建點擊數的空列表 25 mathlist=[] 26 #為儲存數據創立空列表 27 alist=[] 28 29 #用BeautifulSoup進行html的解析 30 html = r.text 31 soup=BeautifulSoup(html,'html.parser') 32 #找到所對應的標簽 33 #用for遍歷循環find_all查找語句查找標題 34 for a in soup.find_all("a","title-link"): 35 titlelist.append(a.string) 36 37 #同理找視頻的點擊數 38 for div in soup.find_all("div","qy-top-title-zhishu"): 39 mathlist.append(div.string) 40 41 print("-------------------------愛奇藝影評榜前25-------------------------") 42 print("{:^10}\t{:^30}\t{:^20}".format("排名","電影名","點擊數")) 43 44 #獲取愛奇藝影評榜前25名 45 for i in range(25): 46 print("{:^10}\t{:^30}\t{:^20}".format(i+1,titlelist[i],mathlist[i])) 47 48 #將獲取的數據放入alist的空列表中 49 for i in range(25): 50 alist.append([i+1,titlelist[i],mathlist[i]]) 51 52 #用pandas對數據進行儲存,做到數據的持久化 53 A = pd.DataFrame(alist,columns = ['排名','電影名','點擊數']) 54 A.to_excel('愛奇藝排行.xlsx') 55 56 #讀取文件中的信息 57 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) 58 #打印出所有的信息 59 df.head(25) 60 61 #根據具體的需求可以清除不需要的數據 62 df.drop("點擊數", axis=1,inplace=True) 63 df.head(10) 64 65 #重復值的處理 66 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) 67 df.duplicated() 68 69 #異常值的觀察 70 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) 71 df.describe() 72 73 #查看相關系數 74 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) 75 df.corr() 76 77 #排名和點擊數的線性關系 78 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) 79 sns.lmplot(x="排名",y= "點擊數",data=df) 80 81 #讀取愛奇藝排行.xlsx將其中的電影名寫到txt文本中去 82 Name = pd.read_excel("愛奇藝排行.xlsx", encoding='utf-8') 83 with open("電影名.txt",'a+', encoding='utf-8') as f: 84 for title in Name.電影名: 85 f.write((str(title)+'\n')) 86 87 #讀取電影名.txt文本 88 text=open('電影名.txt',encoding='utf-8').read() 89 #詞雲的背景圖片 90 photo=imread('手牽手.jpg') 91 Cyun=WordCloud( 92 background_color = "white", 93 mask = photo, 94 width=1600, 95 repeat=True, 96 font_path=r'simfang.ttf', 97 height=1600).generate(text) 98 plt.imshow(Cyun) 99 plt.axis("off") 100 plt.show() 101 #保存詞雲圖片 102 Cyun.to_file("愛奇藝詞雲.jpg") 103 104 #定義一個散點圖的函數 105 #排名與點擊數的散點圖 106 def Sspot(): 107 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) 108 #賦予x,y所對應的值 109 x = df.排名 110 y = df.點擊數 111 plt.xlabel("排名") 112 plt.ylabel("點擊數") 113 plt.scatter(x,y,color="green",label="散點") 114 plt.title("排名與點擊數的散點圖") 115 plt.legend() 116 plt.show() 117 Sspot() 118 119 #繪制扇形圖 120 def Pspot(): 121 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) 122 x = df.電影名 123 y = df.點擊數 124 #前五名的電影標題 125 name = [x[0],x[1],x[2],x[3],x[4]] 126 math = [y[0],y[1],y[2],y[3],y[4]] 127 explode=[0.1,0.1,0.1,0.1,0.1] 128 plt.pie(math,labels=name,colors=["r","g","c","b","y"],explode=explode) 129 plt.axis("equal") 130 plt.title("排名與電影的扇形圖") 131 plt.show() 132 Pspot() 133 134 #排名與點擊數的條形圖 135 def Tspot(): 136 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) 137 x = df.排名 138 y = df.點擊數 139 plt.xlabel("排名") 140 plt.ylabel("點擊數") 141 plt.bar(x,y,color="green") 142 plt.title("排名與點擊數的條形圖") 143 plt.show() 144 Tspot() 145 146 #前五名的電影與點擊數的條形圖 147 def Tspot2(): 148 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) 149 x = df.電影名[:5] 150 y = df.點擊數[:5] 151 plt.xlabel("電影名") 152 plt.ylabel("點擊數") 153 plt.bar(x,y,color="green") 154 plt.title("電影名與點擊數的條形圖") 155 plt.show() 156 Tspot2() 157 158 #排名與點擊數的折線圖 159 def Zspot(): 160 df = pd.DataFrame(pd.read_excel('愛奇藝排行.xlsx')) 161 x = df.排名 162 y = df.點擊數 163 plt.xlabel("排名") 164 plt.ylabel("點擊數") 165 plt.plot(x,y,color="green",label="折線") 166 plt.title("排名與點擊數的折線圖") 167 plt.legend() 168 plt.show() 169 Zspot() 170 171 #回歸直線的圖 172 def huigui(): 173 #x,y為回歸直線的排名和點擊數 174 x = df.排名 175 y = df.點擊數 176 #X,Y為散點圖的 177 X = df.排名 178 Y = df.點擊數 179 #先定義所需要的數據 180 x_i2=0 181 x_i =0 182 y_i=0 183 #計算出x,y的均值用mean() 184 q = x.mean() 185 w = y.mean() 186 for i in range(25): 187 x_i2 = x_i+x[i]*x[i] 188 x_i = x_i+x[i] 189 y_i = y_i+y[i] 190 #運用回歸直線的公式計算出所需要的值 191 #分子 192 m_1 = x_i*y_i-25*q*w 193 #分母 194 m_2 = x_i2-25*q*q 195 #斜率 196 k = m_1/m_2 197 #截距 198 b = w-q*k 199 x=np.linspace(0,25) 200 y=k*x+b 201 print("斜率k=",k,"截距b=",b) 202 plt.figure(figsize=(6,4)) 203 plt.xlabel('排名') 204 plt.ylabel('點擊數') 205 plt.scatter(X,Y,color="green",label="散點",linewidth=2) 206 plt.plot(x, y,color="blue",label= "回歸直線") 207 plt.title("回歸直線圖") 208 plt.legend() 209 plt.show() 210 huigui()
四、結論
根據數據的圖形分析,點擊數會隨着排名的降低呈現大幅度的下降,根據點擊數的數量差距可以知道他們排名差距程度的多少。
小結:在完成程序的過程,有意外獲得的收獲也有一些困難,由於一個的函數字母的輸入的錯誤導致代碼無法運行。所以造就了我現在寫代碼要檢查的習慣,不斷的探索和學習,我對python的語法函數更加精煉。本次任務,我受益良多。