Open In App

Getting value after button click with BeautifulSoup

The library, BeautifulSoup in Python apart from extracting data out of HTML or XML files, helps in searching, modifying, and navigating the parse tree. Are you not able to obtain the value from a widget after the button click? Don’t worry. Just read the article thoroughly to know the procedure of obtaining the value after button click with BeautifulSoup.

Step-by-step Approach:

from bs4 import BeautifulSoup as bs



from tkinter import *

import os



base=os.path.dirname(os.path.abspath(‘#Name of Python file in which you are currently working))

html=open(os.path.join(base, ‘#Name of HTML file from which you wish to read value’))

soup=bs(html, ‘html.parser’)

value=soup.find(“#Name of widget”, {“id”:”#Id name of the widget”}).text

app=Tk()

app.title(“#Title of the app”)

app.geometry(‘#Geometry you wish to give to app’)

def func():

with open(‘#Name of text file in which you wish to write value’, “w”, encoding=’utf-8′) as f_output:

f_output.write(value)

b1=Button(app, text=’#Text you want to give to button’, command=func)

b1.grid(padx=#Padding from x-axis, pady=#Padding from y-axis)

app.mainloop( )

Implementation:

Consider the following HTML source code.




<!DOCTYPE html>
<html>
 <head>
   My First Heading
 </head>
 <body>
   <ul id="list">
     Fruits
     <li>Apple</li>
     <li>Banana</li>
     <li id="here">Mango</li>
   </ul>
  </body>
</html>

Let us consider you want to obtain the value ‘Mango’ in the txt file ‘text_file’ after the button click ‘Click here!’, then you can write the following code.




# Python program to obtain value after button click
  
# Import the libraries BeautifulSoup, tkinter and os
from bs4 import BeautifulSoup as bs
import os
from tkinter import *
  
# Remove the last segment of the path
base = os.path.dirname(os.path.abspath('gfg3.py'))
  
# Open the HTML in which you want to make changes
html = open(os.path.join(base, 'gfg.html'))
  
# Parse HTML file in Beautiful Soup
soup = bs(html, 'html.parser')
  
# Find the value which you want to obtain after button click
value = soup.find("li", {"id": "here"}).text
  
# Construct the app for clicking of button
app = Tk()
  
# Give title to your GUI app
app.title("Vinayak App")
  
# Set dimensions for the app
app.geometry('600x400')
  
  
def apple():
  
    # Open the file in which you want to obtain the value
    with open('text_file.txt', "w", encoding='utf-8') as f_output:
  
        # Writing the value in the file
        f_output.write(value)
  
  
# Construct the button in your app
b1 = Button(app, text='Click Here!', command=apple)
  
# Display the button created in previous step
b1.grid(padx=250, pady=150)
  
# Make the loop for displaying app
app.mainloop()

Output:


Article Tags :