VOOZH about

URL: https://www.geeksforgeeks.org/python/get-data-inside-a-button-tag-using-beautifulsoup/

⇱ Get data inside a button tag using BeautifulSoup - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Get data inside a button tag using BeautifulSoup

Last Updated : 26 Mar, 2021

Sometimes while working with BeautifulSoup, are you stuck at the point where you have to get data inside a button tag? Don't worry. Just read the article and get to know how you can do the same.

For instance, consider this simple page source having a button tag.

Once you have created the button in the HTML code, you can get the text inside a button tag using:

btn_text=btn.text
print(btn_text)

Also, you can find the onclick link of the button inside a button tag using:

btn_onclick=btn['onclick']
print(btn_onclick)

Steps to get the text inside the Button

Step 1: First, import the libraries Beautiful Soup and os.

from bs4 import BeautifulSoup as bs
import os

Step 2: Now, remove the last segment of the path by entering the name of the Python file in which you are currently working.

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

Step 3: Then, open the HTML file from which you want to read the value.

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

Step 4: Moreover, parse the HTML file in Beautiful Soup

soup=bs(html, 'html.parser')

Step 5: Next, find the button for which you want to obtain the data.

btn=soup.find("button", {"id":"#Id name of the button"})

Step 6: Now, for obtaining the text stored inside the button tag in the HTML, use:

btn_text=btn.text

Step 7: Further, for finding the onclick link inside the button tag, you can write the code as follows:

btn_onclick=btn['onclick']

Step 8: Finally, printing the text and onclick link of the button tag obtained in steps 6 and 7.

print(btn_text)
print(btn_onclick)

Below is the full implementation:

Output:

Comment