利用爬虫获取豆瓣电影简介信息,其中增加了可视化功能!代码如下:
import tkinter as tk
import requests
from bs4 import BeautifulSoup
import json
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0'}
def search_movie():
try:
keyword = entry.get()
url = f"https://movie.douban.com/j/subject_suggest?q={keyword}"
response = requests.get(url=url, headers=header)
output = response.text
data = json.loads(output)
id = data[0]['id']
title = data[0]['title']
new_url = f"https://movie.douban.com/subject/{id}/"
response = requests.post(new_url, headers=header)
content = response.text
soup = BeautifulSoup(content, 'html.parser')
head_contents = soup.find('head')
description = get_info(head_contents)
show_info(title, description)
except Exception as e:
show_info("错误", "查询出错了,换一个试试吧!!!!")
def get_info(head_contents):
content = head_contents.find('script', {'type': 'application/ld+json'})
if content:
data = json.loads(str(content.string))
description = data['description']
return description
def show_info(movie, description):
result_text.delete('1.0', tk.END)
result_text.insert(tk.END, f"电影: {movie}\n电影简介: {description}")
result_text.configure(font=("Arial", 12, "bold"))
if __name__ == '__main__':
# 创建主窗口
window = tk.Tk()
window.title("电影查询")
window.geometry("400x300")
# 创建输入框和提示信息
entry = tk.Entry(window, width=30)
entry.insert(tk.END, "请输入电影名")
entry.pack(pady=10)
entry.configure(font=("Arial", 12, "bold"))
# 绑定鼠标点击事件
def clear_content(event):
entry.delete(0, tk.END)
entry.bind("<Button-1>", clear_content)
def on_enter(event):
search_movie()
entry.bind("<Return>", on_enter)
# 创建查询按钮
button = tk.Button(window, text="查询", command=search_movie)
button.configure(font=("Arial", 12, "bold"))
button.pack(pady=5)
# 创建简介描述框
result_text = tk.Text(window, width=40, height=10)
result_text.pack(pady=10)
result_text.size = 20
window.mainloop()