Amazing-Python-Scripts

Форк
0
106 строк · 2.8 Кб
1
from bs4 import BeautifulSoup
2
import requests
3
from tkinter import *
4

5
info_dict = {}
6

7

8
def error_box():
9
    """
10
    A function to create a pop-up, in case the code errors out
11
    """
12
    global mini_pop
13

14
    mini_pop = Toplevel()
15
    mini_pop.title('Error screen')
16

17
    mini_l = Label(mini_pop, text=" !!!\nERROR FETCHING DATA",
18
                   fg='red', font=('Arial', 10, 'bold'))
19
    mini_l.grid(row=1, column=1, sticky='nsew')
20
    entry_str.set("")
21

22

23
def wikiScraper():
24
    """
25
    Function scrapes the infobox lying under the right tags and displays 
26
    the data obtained from it in a new window
27
    """
28
    global info_dict
29

30
    # Modifying the user input to make it suitable for the URL
31
    entry = entry_str.get()
32
    entry = entry.split()
33
    query = '_'.join([i.capitalize() for i in entry])
34
    req = requests.get('https://en.wikipedia.org/wiki/'+query)
35

36
    # to check for valid URL
37
    if req.status_code == 200:
38
        # for parsing through the html text
39
        soup = BeautifulSoup(req.text, 'html.parser')
40

41
        # Finding text within infobox and storing it in a dictionary
42
        info_table = soup.find('table', {'class': 'infobox'})
43

44
        try:
45
            for tr in info_table.find_all('tr'):
46
                try:
47
                    if tr.find('th'):
48
                        info_dict[tr.find('th').text] = tr.find('td').text
49
                except:
50
                    pass
51

52
        except:
53
            error_box()
54

55
        # Creating a pop up window to show the results
56
        global popup
57
        popup = Toplevel()
58
        popup.title(query)
59

60
        r = 1
61

62
        for k, v in info_dict.items():
63
            e1 = Label(popup, text=k+" : ", bg='cyan4',
64
                       font=('Arial', 10, 'bold'))
65
            e1.grid(row=r, column=1, sticky='nsew')
66

67
            e2 = Label(popup, text=info_dict[k], bg="cyan2", font=(
68
                'Arial', 10, 'bold'))
69
            e2.grid(row=r, column=2, sticky='nsew')
70

71
            r += 1
72
            e3 = Label(popup, text='', font=('Arial', 10, 'bold'))
73
            e3.grid(row=r, sticky='s')
74
            r += 1
75

76
        entry_str.set("")
77
        info_dict = {}
78

79
    else:
80
        print('Invalid URL')
81
        error_box()
82

83

84
# Creating a window to take user search queries
85
root = Tk()
86
root.title('Wikipedia Infobox')
87

88
global entry_str
89
entry_str = StringVar()
90

91
search_label = LabelFrame(root, text="Search: ",
92
                          font=('Century Schoolbook L', 17))
93
search_label.pack(pady=10, padx=10)
94

95
user_entry = Entry(search_label, textvariable=entry_str,
96
                   font=('Century Schoolbook L', 17))
97
user_entry.pack(pady=10, padx=10)
98

99
button_frame = Frame(root)
100
button_frame.pack(pady=10)
101

102
submit_bt = Button(button_frame, text='Submit',
103
                   command=wikiScraper, font=('Century Schoolbook L', 17))
104
submit_bt.grid(row=0, column=0)
105

106
root.mainloop()
107

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.