网络爬虫猫眼的最高票房的两部电影代码项目
时间: 2023-09-26 09:07:30 浏览: 80
以下是使用 Python 语言编写的爬虫项目代码,用于获取猫眼电影网站上最高票房的两部电影:
```python
import requests
from bs4 import BeautifulSoup
import csv
def get_movie_info(url):
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')
movie_list = soup.find_all('div', class_='movie-item-info')
data = []
for i in range(2):
movie = movie_list[i]
name = movie.find('p', class_='name').text
star = movie.find('p', class_='star').text.strip()[3:]
release_time = movie.find('p', class_='releasetime').text[5:]
data.append([name, star, release_time])
return data
def save_to_csv(data):
with open('movie.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(['电影名称', '主演', '上映时间'])
writer.writerows(data)
print('数据已保存到 movie.csv 文件中')
if __name__ == '__main__':
url = 'https://maoyan.com/board/1'
data = get_movie_info(url)
save_to_csv(data)
```
运行上述代码后,即可在当前目录下生成一个名为 movie.csv 的文件,并将最高票房的两部电影的名称、主演和上映时间保存在该文件中。
阅读全文