Python爬虫---爬取豆瓣top250的数据和可视化

1.导入相应的库

import requests
headers = {
        'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/1'
}
response = requests.get('https://movie.douban.com/top250',headers=headers)
response
response.text

2.使用正则表达式解析

import re
title = re.findall('<span class="title">(.*?)</span>', response.text,re.S)
title

 

或者,使用BeautifulSoup解析(推荐)

import requests
from bs4 import BeautifulSoup
import csv
 
'''爬取豆瓣电影top20'''
def top250_crawer(url,sum):
    headers = {
        'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/1'
 
    }
 
    response = requests.get(url,headers = headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    # print(soup)
    movie_items = soup.find_all('div', class_='item')
    i = sum+1
    for item in movie_items:
         title = item.select_one('.title').text
         # print(title)
         rating = item.select_one('.rating_num').text
         data = item.select('.bd p')[0].text.split('\n')
         time = data[2].replace(' ','').split('/')[0]
         country = data[2].replace(' ','').split('/')[1]
         print(str(i)+'.'+title+','+country+','+time)
 
         i +=1
 
url = 'https://movie.douban.com/top250'
sum =0
'遍历10页数据,250条结果'
for a in range(10):
    if sum == 0 :
        top250_crawer(url,sum)
        sum +=25
    else:
        page = '?start='+str(sum)+'&filter='
        new_url = url+page
        top250_crawer(new_url,sum)
        sum +=25     

4.将获取到的豆瓣评分数据以词云的方式展示

import jieba
import matplotlib.pyplot as plt
import PIL.Image as image
from wordcloud import WordCloud,STOPWORDS
import numpy as np
with open('./豆瓣电影评分数据.txt', 'r', encoding='utf-8') as f:
    content = f.read()
word_list=jieba.cut(content)
new_list="".join(word_list)
wordcloud=WordCloud(background_color="white",font_path="C:\Windows\Fonts\msyh.ttc").generate(new_list)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南星6603

你的打赏就是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值