Python爬虫案例分享【爬取豆瓣电影排行榜的电影名称和评分】

时间:2024-01-21 18:30:04

注意:在运行此代码之前,请确保已安装requestsbeautifulsoup4

pip install requests beautifulsoup4

代码如下

import requests
from bs4 import BeautifulSoup

url = 'https://movie.douban.com/chart'  # 豆瓣电影排行榜页面

# 发送GET请求获取页面内容
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 解析页面获取电影名称和评分
movies = soup.find_all('div', class_='pl2')
for movie in movies:
    name = movie.find('a').text.strip()
    rating = movie.find('span', class_='rating_nums').text.strip()
    print('电影名称:', name, '评分:', rating)