BeautifulSoup के साथ वेबपेज को डेटा में बदलना: हाइपरलिंक निकालना
इस अभ्यास में, आप BDFL के वेबपेज से हाइपरलिंक के URL कैसे निकाले, यह समझेंगे. इस दौरान, आप find_all() नामक soup मेथड के अच्छे दोस्त बन जाएँगे.
यह अभ्यास पाठ्यक्रम का हिस्सा है
इंटरमीडिएट Importing Data in Python
अभ्यास निर्देश
soupमें सभी हाइपरलिंक ढूंढने के लिएfind_all()मेथड का उपयोग करें. ध्यान रखें कि हाइपरलिंक HTML tag<a>से परिभाषित होते हैं, परfind_all()को यह tag एंगल ब्रैकेट के बिना पास किया जाता है. परिणाम को वैरिएबलa_tagsमें स्टोर करें.- वैरिएबल
a_tagsएक results set है. अब आपका काम है इस परforलूप चलाकर हाइपरलिंक के असली URL प्रिंट करना. ऐसा करने के लिए,a_tagsमें हर तत्वlinkके लिएprint()मेंlink.get('href')पास करें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# Import packages
import requests
from bs4 import BeautifulSoup
# Specify url
url = 'https://www.python.org/~guido/'
# Package the request, send the request and catch the response: r
r = requests.get(url)
# Extracts the response as html: html_doc
html_doc = r.text
# create a BeautifulSoup object from the HTML: soup
soup = BeautifulSoup(html_doc)
# Print the title of Guido's webpage
print(soup.title)
# Find all 'a' tags (which define hyperlinks): a_tags
# Print the URLs to the shell
for ____ in ____:
____