python随机爬取五位电影演员数据并可视化

发布时间 2023-05-28 23:45:43作者: YE-

python随机爬取五位电影演员数据

为了演示如何使用Python随机爬取五位电影演员数据,需要以下步骤:

安装所需的Python库:requests, BeautifulSoup和random
确定你要从哪个网站爬取数据。这个例子中,我们将使用IMDb。
确定你要爬取哪些电影演员。这个例子中,我们将爬取最受欢迎的电影演员。
编写Python脚本代码,以从IMDb网站上获取数据。

下面是一个示例脚本,可以随机爬取五位电影演员数据:

import requests
from bs4 import BeautifulSoup
import random

url = "https://www.imdb.com/chart/starmeter/"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')

actors = soup.find_all('td', class_='titleColumn')

random_actors = random.sample(actors, 5)

for actor in random_actors:
    name = actor.find('a').text.strip()
    rank = actor.find('span', class_='secondaryInfo').text.strip()
    print(f"{name} (Rank: {rank})")

解释一下代码:
首先,我们导入所需的库,包括requests和BeautifulSoup。
然后,我们定义变量url,设置要爬取的网页链接。
我们还定义headers,其中包含了 User-Agent,用于模拟一个合法的用户在访问该网站。
使用requests.get方法发送请求并获取响应。
接下来,我们使用BeautifulSoup解析HTML响应。我们查找' td '元素,并使用CSS类'titleColumn'进行过滤来获取所有电影演员数据。
我们使用random.sample方法获取5个随机电影演员。
最后,我们循环遍历五个演员,获取演员名称和排名并将其打印到控制台中。
希望这个示例代码对你有所帮助。请注意,在爬取网站上的数据时,确保遵守相关法律和道德准则。

可视化上述结果

要可视化上述结果,我们可以使用Python中的matplotlib库。我们可以将演员排名绘制成一个条形图。这里是一个示例代码:

import requests
from bs4 import BeautifulSoup
import random
import matplotlib.pyplot as plt

url = "https://www.imdb.com/chart/starmeter/"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')

actors = soup.find_all('td', class_='titleColumn')

random_actors = random.sample(actors, 5)

names = []
ranks = []

for actor in random_actors:
    name = actor.find('a').text.strip()
    rank = int(actor.find('span', class_='secondaryInfo').text.strip().replace(',', ''))
    names.append(name)
    ranks.append(rank)

fig, ax = plt.subplots()
ax.bar(names, ranks)
ax.set_xlabel('Actor')
ax.set_ylabel('Rank')
ax.set_title('Randomly Selected Actors and Their Ranks')
plt.show()

解释一下代码:
与之前的代码类似,我们首先导入所需的库,包括requests、BeautifulSoup、random、matplotlib。
我们定义了一个空列表'names'和'ranks',用于存储演员名称和排名的数据。
我们遍历五个随机演员,获取他们的名称和排名,并将它们添加到列表'names'和'ranks'中。
然后,我们使用matplotlib库生成一个条形图。我们调用ax.bar方法并传入演员名称和排名数据。我们还设置x轴、y轴和标题的标签。
最后,我们使用plt.show方法来显示图表。
希望这个示例代码对你有所帮助,让你更好地理解如何使用Python将数据可视化。