Sunday, November 17, 2024
Google search engine
HomeLanguagesGet data inside a button tag using BeautifulSoup

Get data inside a button tag using BeautifulSoup

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.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Apple</title>
</head>
<body>
  <button id="enjoy" onclick="gfg.html">
      Click Me!
  </button>
</body>
</html>


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:

Python




# Python program to get data inside
# a button tag using BeautifulSoup
  
# Import the libraries BeautifulSoup 
# and os
from bs4 import BeautifulSoup as bs
import os
  
# Remove the last segment of the path
base = os.path.dirname(os.path.abspath(__file__))
  
# Open the HTML in which you want to make
# changes
html = open(os.path.join(base, 'run.html'))
  
# Parse HTML file in Beautiful Soup
soup = bs(html, 'html.parser')
  
# Finding the location of button
btn = soup.find("button", {"id": "enjoy"})
  
# Obtaining the text stored inside button tag
btn_text = btn.text
  
# Obtaining the onclick link of button tag
btn_onclick = btn['onclick']
  
# Printing the values
print(btn_text)
print(btn_onclick)


Output:

RELATED ARTICLES

Most Popular

Recent Comments