用pycharm爬虫豆瓣电影网站,对所有的数据中电影类型进行one-hot编码
时间: 2024-05-12 08:18:47 浏览: 5
以下是一个示例代码,用于爬取豆瓣电影网站的电影数据并对电影类型进行one-hot编码:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
# 爬取豆瓣电影网站
url = 'https://movie.douban.com/top250'
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)
# 解析HTML页面
soup = BeautifulSoup(response.text, 'html.parser')
movie_list = soup.find_all('div', class_='info')
movies = []
# 提取电影信息
for movie in movie_list:
title = movie.find('span', class_='title').text
score = movie.find('span', class_='rating_num').text
director = movie.find('div', class_='bd').find_all('span')[1].text.replace('\n', '').replace(' ', '')
actors = movie.find('div', class_='bd').find_all('p')[0].text.replace('\n', '').replace(' ', '')
year = movie.find('div', class_='bd').find_all('span')[3].text.replace('\n', '').replace(' ', '')
type = movie.find('div', class_='bd').find_all('span')[4].text.replace('\n', '').replace(' ', '').split('/')
movies.append([title, score, director, actors, year, type])
# 创建DataFrame对象
df = pd.DataFrame(movies, columns=['title', 'score', 'director', 'actors', 'year', 'type'])
# 对电影类型进行one-hot编码
types = df['type'].str.join('|').str.get_dummies()
df = pd.concat([df, types], axis=1)
df = df.drop('type', axis=1)
# 输出结果
print(df.head())
```
这个代码首先爬取豆瓣电影网站的电影数据,并提取电影的标题、评分、导演、演员、年份和类型等信息。然后使用pandas库创建一个DataFrame对象,并对电影类型进行one-hot编码。最后输出结果。