作業(yè)
內(nèi)容
- 導(dǎo)入包
import requests #請(qǐng)求
from lxml import html#解析
from matplotlib import pyplot as plt#繪圖
#繪圖漢字編碼
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
-導(dǎo)入域名
url ='http://movie.douban.com/cinema/later/chongqing/'#豆瓣重慶影訊
-將爬取到的電影信息按"想看人數(shù)的由多到少"排序輸出
info_list=[]#存電影信息
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
with open('douban.html','w',encoding='utf-8') as f:
f.write(html_data)
# print(resp.text)
selector = html.fromstring(html_data)
movie_list = selector.xpath('//div[@id="showing-soon"]/div')
print(movie_list)
name_list = selector.xpath('//div[@id="showing-soon"]/div/div/h3/a/text()')
# print(name_list)
cishu=0
for i in movie_list:
# 電影名稱
name=i.xpath('//div[@id="showing-soon"]/div/div/h3/a/text()')[cishu]
# print(name)
# 上映日期
date=i.xpath('//div[@id="showing-soon"]/div/div/ul/li[1]/text()')[cishu]
# 類型
type=i.xpath('//div[@id="showing-soon"]/div/div/ul/li[2]/text()')[cishu]
# 上映國(guó)家
country=i.xpath('//div[@id="showing-soon"]/div/div/ul/li[3]/text()')[cishu]
# 想看人數(shù)
people=i.xpath('//div[@id="showing-soon"]/div/div/ul/li[4]/span/text()')[cishu]
# cishu+=1
people=int(people.replace('人想看',' '))
info_list.append({
'name':name,
'date':date,
'type':type,
'country':country,
'people':people
})
# print(info_list)
cishu += 1
info_list.sort(key=lambda x:x['people'], reverse=True)
for m in info_list:
print(m)
-繪制上映電影國(guó)家占比圖
#上映國(guó)家
country_list=[]
for i in info_list:
country_list.append(i['country'])
cou = {}#將國(guó)家與次數(shù)弄成一個(gè)鍵值對(duì)
for word in country_list:
cou[word]=cou.get(word, 0)+1
print(len(cou))
times = list(cou.items())
coun=[]#國(guó)家放在一個(gè)列表
cons=[] #次數(shù)放在一個(gè)列表
for i in range(len(cou)):
guojia,ci=times[i]
guojia=str(guojia)
ci=int(ci)
coun.append(guojia)
cons.append(ci)
print(coun)#輸出國(guó)家
print(cons)#輸出次數(shù)
#繪制占比圖
# 距離圓心點(diǎn)距離
explode = [0.1, 0, 0, 0]
colors = ['red', 'purple', 'blue', 'yellow']
plt.pie(cons, explode=explode, shadow=True, labels=coun, autopct='%1.1f%%', colors=colors)
plt.legend(loc=2)
plt.axis('equal')
plt.show()
-占比圖:
上映電影國(guó)家占比圖
-繪制top5最想看電影
上面已經(jīng)給電影信息排過名了
top5_movie = [info_list[i] for i in range(5)]
print(top5_movie)
x=[x['name'] for x in top5_movie]
y=[x['people'] for x in top5_movie]
plt.barh(x,y)
plt.show()
-
Top5最想看電影圖:
Top5最想看電影圖