How to extract social media links from a website in Python

Checked on 2026-11-24.

A company's social profiles are usually links on its own website: icons in the header or footer, and sometimes a list of profile addresses in its structured data. A short Python script can collect both, as long as it can tell a profile from a share button or a single post. The Pipefetch website contacts endpoint returns the same as JSON, sorted by platform.

Where the links are

  • Ordinary links. The row of icons in a footer is a set of <a href> elements pointing at linkedin.com, x.com, instagram.com and the rest. A footer is usually part of every page, so the home page is the place to start.
  • schema.org sameAs. Some sites describe their organization in a JSON-LD block. schema.org defines sameAs as the "URL of a reference Web page that unambiguously indicates the item's identity", and Google's Organization markup guide gives "a URL to your organization's profile page on a social media or review site" as its example and adds: "You can provide multiple sameAs URLs."
  • Links that are not profiles. A share button is a link to the network too. X documents its Web Intents at addresses such as x.com/intent/tweet; its follow intent, x.com/intent/follow?screen_name=NASA, does name an account. Facebook's Share Dialog lives at www.facebook.com/dialog/share. A link to one post, Reel or video is not the profile either.

1. Requests and Beautiful Soup

The script reads one page, takes every link and every sameAs address, keeps those on a known network, drops share buttons and single posts, and cuts each profile address down to the account.

Python
# pip install requests beautifulsoup4
import json
from urllib.parse import parse_qs, urljoin, urlparse

import requests
from bs4 import BeautifulSoup

PLATFORMS = {
    "linkedin.com": "linkedin", "x.com": "x", "twitter.com": "x", "facebook.com": "facebook",
    "instagram.com": "instagram", "youtube.com": "youtube", "tiktok.com": "tiktok",
    "pinterest.com": "pinterest", "github.com": "github",
}
# first parts of a path that make a link a share button, a post or a video rather than a profile
NOT_PROFILE = {
    "intent", "share", "sharer", "sharer.php", "dialog", "sharing", "sharearticle",
    "p", "reel", "reels", "watch", "shorts", "embed", "pin", "hashtag",
}
# first parts that need the second: linkedin.com/company/apify, youtube.com/channel/UC...
TWO_PART = {"company", "in", "school", "showcase", "channel", "c", "user"}


def platform_of(host):
    host = (host or "").lower()
    for domain, name in PLATFORMS.items():
        if host == domain or host.endswith("." + domain):
            return name
    return None


def profile(address):
    """(platform, profile address) for a link to a profile, None for anything else."""
    parts = urlparse(address)
    name = platform_of(parts.hostname)
    path = [part for part in parts.path.split("/") if part]
    if not name or not path:
        return None
    if name == "x" and path[:2] in (["intent", "follow"], ["intent", "user"]):
        handle = parse_qs(parts.query).get("screen_name", [""])[0]   # these two intents name the account
        return (name, f"https://x.com/{handle}") if handle else None
    if path[0].lower() in NOT_PROFILE or "status" in path or "video" in path:   # .../status/123: one post
        return None
    keep = 2 if path[0].lower() in TWO_PART and len(path) > 1 else 1
    return name, f"https://{parts.hostname.lower()}/{'/'.join(path[:keep])}"


def same_as(node):
    """Every sameAs address in a JSON-LD value, however deep."""
    found = []
    if isinstance(node, dict):
        value = node.get("sameAs")
        if isinstance(value, str):
            found.append(value)
        elif isinstance(value, list):
            found += [item for item in value if isinstance(item, str)]
        for child in node.values():
            found += same_as(child)
    elif isinstance(node, list):
        for item in node:
            found += same_as(item)
    return found


def social_links(url):
    res = requests.get(url, timeout=15)
    res.raise_for_status()
    soup = BeautifulSoup(res.text, "html.parser")
    addresses = [urljoin(res.url, a["href"]) for a in soup.find_all("a", href=True)]
    for block in soup.find_all("script", type="application/ld+json"):
        try:
            addresses += same_as(json.loads(block.string or ""))
        except json.JSONDecodeError:
            pass
    found = {}
    for address in addresses:
        hit = profile(address)
        if hit and hit[1] not in found.setdefault(hit[0], []):
            found[hit[0]].append(hit[1])
    return found


print(social_links("https://apify.com"))

It returns a dictionary such as {"linkedin": [...], "x": [...]}, with a list per network, because a company can link several accounts on one network: a regional one, a support one, one per product. To read more pages than the home page, add the contact and about pages the way the email extraction guide does: the loop is the same.

Where it stops:

  • Links that a script inserts after the page loads are not in the HTML that requests receives. Some sites build their whole footer that way.
  • Some sites answer scripts with 403 or a challenge page. Then there is nothing to parse.
  • A link is not proof of ownership. A page can link a partner, the agency that built the site, or a post the company was mentioned in. Compare the account name with the company when it matters.
  • Nothing is checked on the networks themselves: a renamed or deleted account still comes back. Checking means visiting each network, which has its own terms and may ask for a login.
  • The rules in the script (which hosts, which paths are not profiles) are yours to keep current as networks change their addresses.

2. One request: the website contacts endpoint

The Pipefetch website contacts endpoint reads the home page first, then the pages most likely to hold contact details (contact, imprint, about, team), up to the number in pages.

Python
import os
import requests

res = requests.get(
    "https://pipefetch.com/v1/web/contacts",
    params={"url": "apify.com"},   # pages: 1 to 10, 5 by default
    headers={"x-api-key": os.environ["PIPEFETCH_API_KEY"]},
    timeout=90,
)
if res.status_code == 404:
    # no_contacts, website_unreachable or website_blocked: not charged
    print(res.json()["error"]["code"])
else:
    res.raise_for_status()
    data = res.json()["data"]
    for platform, links in data["socials"].items():
        if links:
            print(platform, links)
    print("pages read:", data["pagesRead"])

socials holds 16 platforms, each a list of addresses, empty when the pages read link none. This is the part of our saved answer for apify.com of November 18, 2026:

JSON
{
  "socials": {
    "linkedin": ["https://www.linkedin.com/company/apify"],
    "facebook": [],
    "instagram": [],
    "twitter": ["https://x.com/apify"],
    "youtube": [],
    "tiktok": ["https://www.tiktok.com/@apifytech", "https://www.tiktok.com/@apifyoffice"],
    "pinterest": [], "threads": [], "snapchat": [], "telegram": [], "whatsapp": [],
    "discord": ["https://discord.gg/jyEM2PRvMU", "https://discord.gg/w3e2v7rWDw"],
    "reddit": [],
    "github": ["https://github.com/apify"],
    "bluesky": [], "medium": []
  }
}

X links come under twitter: in that answer, x.com/apify. The same answer carries the emails, phone numbers, contact page and postal address the site publishes, and pagesRead lists the pages that were read. The reference lists every field.

The brand endpoint has a socials list as well, with a platform next to each address, and a twitterHandle taken from the home page's twitter:site tag. It reads the home page only, so for profile links the contacts endpoint, which reads several pages, is the one to use.

Where it stops: pages are read as plain HTML, so links added by JavaScript are not seen, and a site that refuses automated requests answers 404 website_blocked. Only what the website links is returned: nothing is guessed and no network is asked, so follower counts are not in the answer and a dead account is not detected. As the two TikTok accounts above show, you can get more than one address per network and choose yourself.

A request costs 1 credit, and most take 2 to 9 seconds. A site with no email, phone number or social profile on the pages read answers 404 no_contacts, and one that does not answer within about 20 seconds answers 404 website_unreachable; neither costs anything. A site with an email address but no profile links still answers with data and costs 1 credit. A new account has 100 free credits and needs no card. This is not an official API of the websites it reads, and Pipefetch is not affiliated with them.

Which one should you use?

SituationUse
A few sites, or rules you want to control link by linkThe script
A list of company domains, with emails and phone numbers in the same passThe website contacts endpoint
Profiles together with the logo, colors and fontsThe brand endpoint
A site that builds its footer with JavaScriptA browser automation library such as Playwright; neither route here runs JavaScript

After the links: followers and company pages

A profile address is where the next question starts: how many followers, how active, what the company page says. Each network has its own routes and rules, covered in their own guides: LinkedIn company data, Instagram follower counts, YouTube subscriber counts, TikTok follower counts and Facebook Page followers. In Pipefetch, the LinkedIn company endpoint takes a company page address exactly as the contacts endpoint returns it (1 credit), and the Instagram profile endpoint takes a profile address (2 credits).

The accounts a business links are usually the business's own. A small business's profile can be a person's own account, though, and then it is personal data, to which data-protection law such as the GDPR applies. This is not legal advice.

Try it with 100 free credits. No card needed. No scraper to build or maintain. Get an API key or read the docs.

Every source

YouTube

Instagram

TikTok

Facebook

Google

Threads

LinkedIn

App stores

Steam

X

Pinterest

Airbnb

Real estate

Keywords

Job boards

Eventbrite

Shopify stores

Public tenders

All guides