Use BeautifulSoup's find_all() method with "a" as the tag name to get every anchor (<a>) element, then read each link from its href attribute. Here's how to extract all links from ScrapingBee's blog:
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
response = requests.get("https://www.scrapingbee.com/blog/")
soup = BeautifulSoup(response.content, "html.parser")
# Find all <a> elements that have an href attribute
for link in soup.find_all("a", href=True):
url = urljoin(response.url, link["href"]) # Converts relative links to full URLs
print("Link:", url, "Text:", link.get_text(strip=True))
href=True skips anchors without an href, get_text(strip=True) returns the link text even when the <a> tag contains nested tags such as <span>, and urljoin converts relative links such as /blog/page/2/ into full URLs.
Image-only links, like <a href="..."><img src="..."></a>, return an empty string for the text because get_text() doesn't read an image's alt attribute. To get a label for those links, fall back to the image's alt attribute:
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
response = requests.get("https://www.scrapingbee.com/blog/")
soup = BeautifulSoup(response.content, "html.parser")
for link in soup.find_all("a", href=True):
url = urljoin(response.url, link["href"])
text = link.get_text(strip=True)
# No text? Use the image's alt attribute instead
if not text:
img = link.find("img")
if img:
text = img.get("alt", "")
print("Link:", url, "Text:", text)