BeautifulSoup के ज़रिए वेबपेज को डेटा में बदलना: टेक्स्ट निकालना
जैसा वादा किया था, अगले अभ्यासों में आप HTML soup से जानकारी निकालने की बुनियादी बातें सीखेंगे. इस अभ्यास में, आप BDFL के वेबपेज से टेक्स्ट निकालना सीखेंगे और साथ में उस वेबपेज का टाइटल भी प्रिंट करेंगे.
यह अभ्यास पाठ्यक्रम का हिस्सा है
इंटरमीडिएट Importing Data in Python
अभ्यास निर्देश
- सैंपल कोड में HTML response object
html_docपहले से बना हुआ है: आपका पहला काम है इसेBeautifulSoup()फंक्शन से Soupify करना और बनने वाले soup को वैरिएबलsoupमें असाइन करना. - HTML soup
soupसेtitleएट्रिब्यूट के जरिए टाइटल निकालें और उसेguido_titleमें असाइन करें. - Guido के वेबपेज का टाइटल शेल में
print()फंक्शन से प्रिंट करें. - HTML soup
soupसेget_text()मेथड का उपयोग करके टेक्स्ट निकालें और उसेguido_textमें असाइन करें. - टेक्स्ट को शेल में प्रिंट करने के लिए Submit Answer दबाएँ.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# Import packages
import requests
from bs4 import BeautifulSoup
# Specify url: url
url = 'https://www.python.org/~guido/'
# Package the request, send the request and catch the response: r
r = requests.get(url)
# Extract the response as html: html_doc
html_doc = r.text
# Create a BeautifulSoup object from the HTML: soup
# Get the title of Guido's webpage: guido_title
# Print the title of Guido's webpage to the shell
# Get Guido's text: guido_text
# Print Guido's text to the shell
print(guido_text)