Amazing-Python-Scripts
106 строк · 2.8 Кб
1from bs4 import BeautifulSoup
2import requests
3from tkinter import *
4
5info_dict = {}
6
7
8def error_box():
9"""
10A function to create a pop-up, in case the code errors out
11"""
12global mini_pop
13
14mini_pop = Toplevel()
15mini_pop.title('Error screen')
16
17mini_l = Label(mini_pop, text=" !!!\nERROR FETCHING DATA",
18fg='red', font=('Arial', 10, 'bold'))
19mini_l.grid(row=1, column=1, sticky='nsew')
20entry_str.set("")
21
22
23def wikiScraper():
24"""
25Function scrapes the infobox lying under the right tags and displays
26the data obtained from it in a new window
27"""
28global info_dict
29
30# Modifying the user input to make it suitable for the URL
31entry = entry_str.get()
32entry = entry.split()
33query = '_'.join([i.capitalize() for i in entry])
34req = requests.get('https://en.wikipedia.org/wiki/'+query)
35
36# to check for valid URL
37if req.status_code == 200:
38# for parsing through the html text
39soup = BeautifulSoup(req.text, 'html.parser')
40
41# Finding text within infobox and storing it in a dictionary
42info_table = soup.find('table', {'class': 'infobox'})
43
44try:
45for tr in info_table.find_all('tr'):
46try:
47if tr.find('th'):
48info_dict[tr.find('th').text] = tr.find('td').text
49except:
50pass
51
52except:
53error_box()
54
55# Creating a pop up window to show the results
56global popup
57popup = Toplevel()
58popup.title(query)
59
60r = 1
61
62for k, v in info_dict.items():
63e1 = Label(popup, text=k+" : ", bg='cyan4',
64font=('Arial', 10, 'bold'))
65e1.grid(row=r, column=1, sticky='nsew')
66
67e2 = Label(popup, text=info_dict[k], bg="cyan2", font=(
68'Arial', 10, 'bold'))
69e2.grid(row=r, column=2, sticky='nsew')
70
71r += 1
72e3 = Label(popup, text='', font=('Arial', 10, 'bold'))
73e3.grid(row=r, sticky='s')
74r += 1
75
76entry_str.set("")
77info_dict = {}
78
79else:
80print('Invalid URL')
81error_box()
82
83
84# Creating a window to take user search queries
85root = Tk()
86root.title('Wikipedia Infobox')
87
88global entry_str
89entry_str = StringVar()
90
91search_label = LabelFrame(root, text="Search: ",
92font=('Century Schoolbook L', 17))
93search_label.pack(pady=10, padx=10)
94
95user_entry = Entry(search_label, textvariable=entry_str,
96font=('Century Schoolbook L', 17))
97user_entry.pack(pady=10, padx=10)
98
99button_frame = Frame(root)
100button_frame.pack(pady=10)
101
102submit_bt = Button(button_frame, text='Submit',
103command=wikiScraper, font=('Century Schoolbook L', 17))
104submit_bt.grid(row=0, column=0)
105
106root.mainloop()
107