使用Python编写一个脚本,使用BeautifulSoup库抓取豆瓣电影250的信息(包括电影名称、导演、演员、评分等),并将信息存储到本地数据库中。
时间: 2024-03-11 11:45:31 浏览: 130
好的,我可以为您提供一些思路来完成这个任务。
首先,我们需要安装 Beautiful Soup 库和一个 Python 数据库接口。你可以使用 pip 工具来安装这些库:
```
pip install beautifulsoup4
pip install pymysql
```
接下来,我们可以使用 requests 库来获取豆瓣电影250的页面内容,然后使用 Beautiful Soup 库来解析页面内容,获取电影的名称、导演、演员和评分等信息。
```
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/top250'
def get_movies():
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.36'
}
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
movie_list = soup.find('ol', class_='grid_view').find_all('li')
movies = []
for movie in movie_list:
title = movie.find('span', class_='title').text
rating = movie.find('span', class_='rating_num').text
director = movie.find('p').text.split('\n')[1].strip().replace('导演: ', '')
actors = movie.find('p').text.split('\n')[2].strip().replace('主演: ', '')
movies.append({
'title': title,
'rating': rating,
'director': director,
'actors': actors
})
return movies
```
最后,我们可以使用 Python 数据库接口来将获取到的电影信息存储到本地数据库中。
```
import pymysql
host = 'localhost'
user = 'root'
password = 'password'
db = 'douban'
def save_movies(movies):
conn = pymysql.connect(host=host, user=user, password=password, db=db)
cursor = conn.cursor()
for movie in movies:
title = movie['title']
rating = movie['rating']
director = movie['director']
actors = movie['actors']
cursor.execute('INSERT INTO movies (title, rating, director, actors) VALUES (%s, %s, %s, %s)', (title, rating, director, actors))
conn.commit()
cursor.close()
conn.close()
```
这样,我们就完成了任务,可以运行脚本来获取豆瓣电影250的信息并存储到本地数据库中。
```
movies = get_movies()
save_movies(movies)
```
阅读全文