爬取豆瓣top250完整代码并转为json输出
时间: 2023-08-12 17:18:31 浏览: 142
爬取豆瓣电影Top250数据
5星 · 资源好评率100%
以下是爬取豆瓣top250电影并转化为JSON输出的Python代码:
```python
import requests
from bs4 import BeautifulSoup
import json
url = 'https://movie.douban.com/top250'
def get_movies(start):
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'}
params = {
'start': start,
'filter': ''
}
response = requests.get(url, headers=headers, params=params)
soup = BeautifulSoup(response.text, 'html.parser')
movie_list = soup.find_all('div', attrs={'class': 'info'})
movies = []
for movie in movie_list:
title = movie.find('span', attrs={'class': 'title'}).text
rating_num = movie.find('span', attrs={'class': 'rating_num'}).text
quote = movie.find('span', attrs={'class': 'inq'}).text if movie.find('span', attrs={'class': 'inq'}) else ''
link = movie.find('a')['href']
movies.append({'title': title, 'rating_num': rating_num, 'quote': quote, 'link': link})
return movies
movies = []
for i in range(0, 250, 25):
movies += get_movies(i)
with open('douban_top250.json', 'w', encoding='utf-8') as f:
json.dump(movies, f, ensure_ascii=False, indent=4)
```
这段代码通过requests模块向豆瓣top250电影页面发送请求,并使用BeautifulSoup模块解析HTML代码,提取出电影的标题、评分、引言和链接等信息。最后将这些信息转化为一个字典列表,并使用json模块将列表中的字典转化为JSON格式数据,并输出到名为"douban_top250.json"的文件中。
阅读全文