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 definessameAsas 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 atwww.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.
# 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
requestsreceives. 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.
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:
{
"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?
| Situation | Use |
|---|---|
| A few sites, or rules you want to control link by link | The script |
| A list of company domains, with emails and phone numbers in the same pass | The website contacts endpoint |
| Profiles together with the logo, colors and fonts | The brand endpoint |
| A site that builds its footer with JavaScript | A 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.
APIs used in this guide
-
1 credit
Website Contacts API
The emails, phone numbers and social profiles a website publishes, with its contact page, address and company name.
GET /v1/web/contacts -
1 credit
Brand API
The logo, icon, brand colors, fonts, description and social profiles of a company, read from its website.
GET /v1/web/brand -
2 credits
Instagram Profile API
Exact followers, bio, links, account type and engagement of a public Instagram account, with its latest posts and Reels.
GET /v1/instagram/profile -
1 credit
LinkedIn Company API
The public LinkedIn page of a company: industry, size, exact followers, headquarters, website, specialties and its latest posts.
GET /v1/linkedin/company
More Websites guides
- Clearbit Logo API alternatives: get a company logo from its domain
- How to extract email addresses from a website in Python
- How to turn a web page into Markdown in Python
- How to detect what a website is built with, in Python
- How to get the contact emails and phone numbers of websites in Google Sheets
- How to build a LangChain tool that reads web pages and searches Google
- How to turn a web page into Markdown in JavaScript for RAG
- How to get a website's favicon in Python
- How to check robots.txt in Python before you fetch a page
Guides for other sources
Every source
YouTube
- How to get a YouTube transcript in Python
- How to get a YouTube transcript in Node.js
- YouTube API quota exceeded: what the error means and how to fix it
- How to find a YouTube channel ID from a handle or URL
- How to download YouTube subtitles as SRT or VTT
- youtube-transcript-api RequestBlocked or IpBlocked: why it happens and how to fix it
- How to get YouTube comments in Python
- How to search YouTube from Python
- How to list a YouTube channel's videos in Python
- How to summarize a YouTube video with an LLM in Python
- How to get YouTube transcripts and video stats in Google Sheets
- How to get YouTube video views and likes in Python
- How to get YouTube transcripts in n8n, Make and Zapier
- LangChain YoutubeLoader fails on a server: why, and a loader that works
- How to get a YouTube channel's subscriber count in Python
- How to give Claude or Cursor access to YouTube (MCP server)
- How to get YouTube comments in Node.js
- How to analyze YouTube comments with an LLM in Python
- How to list a YouTube channel's Shorts in Python
- How to search YouTube from JavaScript
- How to get an Instagram follower count in Python
- Instagram Basic Display API alternatives: what to use after the shutdown
- Instaloader 401 Unauthorized, 429 and "Login required": what to do
- How to calculate an Instagram engagement rate in Python
- How to get an Instagram follower count in Node.js
- How to get Instagram follower counts in Google Sheets
- How to get Instagram Reel views in Python
TikTok
- How to get a TikTok video's views and likes in Python
- How to get the comments of a TikTok video in Python
- How to get a TikTok follower count in Python
- TikTok Research API: who can get access, and what to do if you cannot
- How to get TikTok video views, likes and shares in Node.js
- How to get TikTok views, likes and follower counts in Google Sheets
- How to get a Facebook Page's posts without app review
- Is there a Facebook Marketplace API?
- Facebook Groups API alternatives after its removal in 2024
- How to get a Facebook Page's follower count and contact details in Python
- How to get Google search results in Python
- pytrends 429 TooManyRequestsError: what it means and what to do
- How to get Google Trends data in Python
- Why is Wyoming first in Google Trends?
- How to get Google search results in Node.js
- How to get Google search results into Google Sheets
- How to give an LLM live Google results with tool calling
Threads
- How to get LinkedIn company data in Python
- How to search LinkedIn jobs from Python
- How to get a LinkedIn company page's latest posts in Python