URL processing¶
Many social media posts contain a link.
A link shows what the author shared, and public lists describe the website behind the link.
A URL is the address of a web page, such as https://www.example.com/news/story.
This notebook uses the words "URL" and "link" for the same thing.
The notebook goes from raw posts to a table of websites. It finds the URLs in the text of posts, expands shortened links, removes tracking parameters, extracts the domain of each link, counts the domains, and joins them to two public lists of domains. The first sections use hand-written posts, and the later sections use one day of real Reddit posts.
Sections: Extract URLs from posts, Expand shortened links, Remove query parameters, Extract the domain, Count domains, Join to a domain list, From scores to categories.
Packages beyond the standard library: urlextract, tldextract, requests, pandas, matplotlib.
Install them with uv add urlextract tldextract requests pandas matplotlib (or pip install).
Colab has all of them except urlextract and tldextract, and the next cell installs these two there.
The notebook downloads four data files of about 5 MB in total. It needs no API key and no GPU. The section "Expand shortened links" sends fewer than ten requests to live websites, so its output can change from one run to the next. No other section depends on these requests.
# Colab does not have urlextract and tldextract, so this cell installs them there.
# pip may print a note about restarting the kernel. A restart is not needed.
# The cell does nothing if the two packages are already installed.
import importlib.util
if importlib.util.find_spec("urlextract") is None:
%pip install -q urlextract
if importlib.util.find_spec("tldextract") is None:
%pip install -q tldextract
# The later sections use one day of Reddit posts about the 2022 U.S. midterm
# elections, from the public MEIU22 dataset. This cell downloads the file (1.1 MB)
# from GitHub into data/ next to this notebook, unless the file is already there.
# The long string in the address is a fixed commit of the repository, so every run
# gets the same file.
import pathlib
import urllib.request
data_url = (
"https://raw.githubusercontent.com/osome-iu/MEIU22/"
"b81de64d5365d22dd3cf95634d9989fdfb7710e5/"
"data/reddit_keyword/reddit_submission_2022-11-08.json.gz"
)
data_path = pathlib.Path("data") / "reddit_submission_2022-11-08.json.gz"
data_path.parent.mkdir(exist_ok=True)
if not data_path.exists():
urllib.request.urlretrieve(data_url, data_path)
print(data_path, data_path.stat().st_size, "bytes")
Extract URLs from posts¶
Some platforms return the links of a post in a separate field. Check the documentation of the API first. When the links are only in the text, you have to find them yourself.
The six posts below are hand-written.
They show the forms that a link takes in a post: with https://, without it, with www., shortened, and followed by punctuation.
posts = [
"A good explainer on how ballots are counted: https://www.example.com/news/2022/how-votes-are-counted?utm_source=reddit&utm_medium=social",
"The video is at https://youtu.be/jNQXAC9IVRw and the paper is at doi.org/10.1093/pan/mpn018",
"County results are on a map (https://www.example.org/results/#map). Refresh often.",
"Read www.nytimes.com/section/politics, then come back.",
"No link in this post, only the hashtag #midterms.",
"I did not expect this.It was close.",
]
urlextract finds URLs in plain text.
It looks for a known ending of a domain name, such as .com or .org, and then extends the match to the left and to the right.
For this reason it also finds a link that does not start with https://.
from urlextract import URLExtract
extractor = URLExtract()
for post in posts:
print(extractor.find_urls(post))
The output has one list for each post.
['https://www.example.com/news/2022/how-votes-are-counted?utm_source=reddit&utm_medium=social']
['https://youtu.be/jNQXAC9IVRw', 'doi.org/10.1093/pan/mpn018']
['https://www.example.org/results/#map']
['www.nytimes.com/section/politics,']
[]
['this.It']
The first three posts are correct.
The tool finds doi.org/10.1093/pan/mpn018, which has no https://, and it leaves out the parentheses around the third link.
Two results are wrong.
- The fourth link ends with a comma. The comma belongs to the sentence, and the tool keeps it as a part of the link.
- The last post has no link. A space is missing after
this., and.itis the ending of Italian domain names, sothis.Itlooks like a domain.
The function below repairs what a rule can repair.
It removes punctuation at the end of a link, and it adds https:// to a link that has no scheme.
The later steps need the scheme.
only_unique=True returns a link once when a post contains it twice.
def extract_urls(text):
"""Return the URLs in a text, without punctuation at the end and with a scheme."""
urls = []
for url in extractor.find_urls(text, only_unique=True):
url = url.rstrip(".,;:!?")
if not url.lower().startswith(("http://", "https://")):
url = "https://" + url
urls.append(url)
return urls
for post in posts:
print(extract_urls(post))
The fourth link is now correct.
The false link https://this.It remains, because no simple rule separates it from a real link.
An error of this kind shows up later as a strange domain with one link.
Removing punctuation at the end can also damage a link, because a real address can end with one of these characters. This case is much less common than a sentence that ends after a link.
Real posts¶
From here on, the notebook also uses real posts. The file that the second cell downloaded comes from MEIU22 (Aiyappa et al., 2023), a public collection of social media posts about the 2022 U.S. midterm elections. The repository has the MIT license. The file holds the Reddit submissions of November 8, 2022, the day of the election, that matched the keywords of the collection. A submission is a post that starts a thread on Reddit.
Each line of the file is one submission as a JSON object with about 60 fields.
The next cell keeps five of them: the title, the text (selftext), the link (url), the community (subreddit), and the time (created_utc).
It leaves out the name of the author and every other field.
It also drops the submissions that Reddit marks as adult content (over_18).
Reddit writes the character & as & in these fields.
html.unescape turns it back into &.
Without this step, the parameters of a link are split in the wrong places.
import gzip
import html
import json
import pandas as pd
keep = ["title", "selftext", "url", "subreddit", "created_utc"]
rows = []
with gzip.open(data_path, "rt", encoding="utf-8") as f:
for line in f:
post = json.loads(line)
if post["over_18"]:
continue
rows.append({field: post.get(field, "") for field in keep})
df = pd.DataFrame(rows)
for column in ["title", "selftext", "url"]:
df[column] = df[column].apply(html.unescape)
# A post on a user profile has the user name in the field subreddit.
on_profile = df["subreddit"].str.startswith("u_")
df.loc[on_profile, "subreddit"] = "user profile"
# Some links hold the name of an account. In each pattern, (?<=...) is the text
# in front of the name, and the rest of the pattern matches the name.
name_patterns = [
r"(?<=/user/)[^/]+", # a post on a Reddit profile, relative address
r"(?<=/r/u_)[^/]+", # a post on a Reddit profile
r"(?<=twitter\.com/)[^/?]+", # the author of a tweet
r"(?<=tiktok\.com/@)[^/?]+", # a TikTok account
r"(?<=twitch\.tv/)[^/?]+", # a Twitch channel
]
with_name = df["url"].str.contains("|".join(name_patterns))
for pattern in name_patterns:
df["url"] = df["url"].str.replace(pattern, "account", regex=True)
print(df.shape)
print(on_profile.sum(), "posts on a user profile")
print(with_name.sum(), "links with the name of an account")
print(pd.to_datetime(df["created_utc"], unit="s").agg(["min", "max"]))
The table has 1,832 submissions, all from November 8, 2022 (UTC). The file has 1,903 lines, and 71 of them are marked as adult content.
210 of the submissions are posts on a user profile.
For these posts, the field subreddit holds u_ followed by the name of the user.
The cell replaces these values with the text user profile, so this column holds no user name.
All posts on user profiles then count as one community.
128 values of url hold the name of an account.
77 are links to tweets, 49 are addresses of posts on user profiles, one is a link to a TikTok account, and one is a link to a Twitch channel.
The cell replaces each name with the word account.
A link to a tweet then has the form https://twitter.com/account/status/....
The rest of each link stays, so the number of distinct links does not change.
Reddit has two kinds of submissions.
- A link post shares a link. Reddit returns the link in the field
url, so nothing has to be extracted. - A text post has a text in
selftext. Itsurlis the address of the post itself on Reddit. Links in the text have to be extracted.
The next cell runs extract_urls on the text of every submission.
It takes a few seconds.
text_urls = df["selftext"].apply(extract_urls)
print((text_urls.str.len() > 0).sum(), "submissions have a URL in the text")
print(text_urls.str.len().sum(), "URLs in total")
214 submissions have at least one URL in the text, and the tool finds 1,289 URLs in them.
The text of a Reddit post is written in Markdown.
Markdown writes a link as [label](address) and puts a backslash before some characters.
urlextract handles most of these links.
The next cell counts the extracted URLs that still contain a piece of Markdown: a backslash, or the characters ]( between two links.
all_text_urls = pd.Series([url for urls in text_urls for url in urls])
odd = all_text_urls.str.contains(r"\\|\]\(")
print(odd.sum(), "of", len(all_text_urls), "extracted URLs contain a piece of Markdown")
43 of the 1,289 URLs are damaged in this way, which is about 3%.
Extraction from text is never perfect. When the platform returns the link in a field, use the field. When you extract links from text, read a sample of the results, and look for the markup of the platform.
Expand shortened links¶
A shortened link is a short address that forwards the visitor to the real address.
Some platforms shorten every outside link, and some users share links from a shortening service.
https://youtu.be/jNQXAC9IVRw is the short form of https://www.youtube.com/watch?v=jNQXAC9IVRw.
A shortened link hides where it goes.
For most services, the only way to find the real address is to ask the service.
expand_url sends an HTTP request and follows the redirects to the last address.
- A
HEADrequest asks for the headers only, so the page itself is not downloaded. timeout=10stops the request when the server does not answer within 10 seconds.- A failed request raises an exception. The function catches it and returns the link unchanged, so one bad link does not stop a long run.
import requests
def expand_url(url, timeout=10):
"""Follow the redirects and return the final URL."""
try:
r = requests.head(url, allow_redirects=True, timeout=timeout)
return r.url
except requests.RequestException:
return url # keep the original URL if the request fails
expand_url("https://doi.org/10.1093/pan/mpn018")
A DOI link is a short link to a paper. On the day this notebook was written, the call returned an address of the publisher that starts like this:
https://www.cambridge.org/core/journals/political-analysis/article/fightin-words-...
The next cell tries three more links.
for url in [
"https://youtu.be/jNQXAC9IVRw",
"https://short.invalid/abc123",
"doi.org/10.1093/pan/mpn018",
]:
print(url, "->", expand_url(url))
https://youtu.be/jNQXAC9IVRw -> https://www.youtube.com/watch?v=jNQXAC9IVRw&feature=youtu.be
https://short.invalid/abc123 -> https://short.invalid/abc123
doi.org/10.1093/pan/mpn018 -> doi.org/10.1093/pan/mpn018
- The first link expands to the long YouTube address. YouTube adds the parameter
feature=youtu.be, which records that the visitor came from a short link. The next section removes parameters of this kind. - The second link fails. No website has a name that ends with
.invalid, so the request raises an exception, and the function returns the link unchanged. - The third link also comes back unchanged. It has no
https://, andrequestsrefuses a link without a scheme. Add the scheme first, asextract_urlsdoes.
What can go wrong¶
The result of this step depends on other websites, so it is the least reliable step of the notebook.
- A request can fail or time out. The function then returns its input, so a failed link looks the same as a link that was never shortened. Count the links that come back unchanged.
- Some sites answer a
HEADrequest with an error. Some sites block requests that come from a program, or from a cloud service such as Colab. The function then returns the last address that it reached. - The last address can be a page that asks for a login or for consent to cookies.
- The target of a link can change after the post was written, and shortening services shut down. An old link can lead to a page that the author did not share.
- Each request takes time, often about a second, and up to the timeout when the server does not answer.
The short links of the Reddit file¶
Send as few requests as you can. Three rules keep the number small.
- Expand only the links of known shortening services. The link posts of this file contain links on
youtu.be. - Expand each distinct link once.
- Pause between two requests to the same site, and save the results, so that a second run does not send the requests again.
is_short = df["url"].str.startswith("https://youtu.be/")
short_links = df.loc[is_short, "url"].drop_duplicates().tolist()
print(is_short.sum(), "links on youtu.be,", len(short_links), "of them distinct")
The 31 links are 9 distinct links. The next cell expands the first five, with a pause of one second after each request.
import time
expanded = {}
for url in short_links[:5]:
expanded[url] = expand_url(url)
time.sleep(1) # pause between two requests to the same site
expanded
Each of the five links should come back as an address that starts with https://www.youtube.com/watch?v=.
If a link comes back unchanged, the request failed.
The dictionary expanded maps each short link to its long form.
For a larger collection, write this dictionary to a file after every few hundred requests.
The MEIU22 repository has a fuller version of this step. It holds a list of about 140 shortening services, and it expands only the links on their domains.
The rest of this notebook does not use expanded, so that every run gives the same numbers.
The section "Count domains" handles youtu.be with a rule that needs no request.
Remove query parameters¶
A URL has up to five parts.
urlsplit from the standard library separates them.
The URL below is hand-written.
from urllib.parse import urlsplit
url = "https://www.example.com/news/2022/how-votes-are-counted?utm_source=reddit&utm_medium=social#comments"
parts = urlsplit(url)
print("scheme: ", parts.scheme)
print("netloc: ", parts.netloc)
print("path: ", parts.path)
print("query: ", parts.query)
print("fragment:", parts.fragment)
scheme: https
netloc: www.example.com
path: /news/2022/how-votes-are-counted
query: utm_source=reddit&utm_medium=social
fragment: comments
- The scheme is
httpsorhttp. - The netloc is the name of the server.
- The path names the page on the server.
- The query follows the
?. It is a list ofkey=valuepairs, which are called query parameters, separated by&. - The fragment follows the
#. It names a position inside the page.
urlsplit needs the scheme.
Without https://, it puts the whole address into the path and leaves the netloc empty.
Many query parameters only track where a visitor came from.
The parameters that start with utm_ are the most common ones: utm_source=reddit tells the website that the visitor clicked the link on Reddit.
The page is the same with and without them.
Without a cleaning step, one article that was shared from five apps counts as five different URLs.
The simplest rule removes the whole query and the fragment.
def strip_query(url):
"""Remove the query and the fragment of a URL."""
return urlsplit(url)._replace(query="", fragment="").geturl()
print(strip_query(url))
print(strip_query("https://www.youtube.com/watch?v=jNQXAC9IVRw&feature=youtu.be"))
https://www.example.com/news/2022/how-votes-are-counted
https://www.youtube.com/watch
The first result is correct.
The second result is wrong.
YouTube keeps the ID of the video in the parameter v, so this rule turns every YouTube video into the same address.
A more careful rule removes only the parameters that are known to track visitors, and keeps the others.
parse_qsl splits a query into pairs, and urlencode joins pairs into a query.
The set tracking_keys starts with five common keys: fbclid and gclid are click IDs that Facebook and Google add, igshid comes from the share button of Instagram, feature is the YouTube parameter from the last section, and ref names a referring site.
from urllib.parse import parse_qsl, urlencode
tracking_keys = {"fbclid", "gclid", "igshid", "feature", "ref"}
def remove_tracking(url):
"""Remove the tracking parameters and the fragment of a URL."""
parts = urlsplit(url)
kept = [
(key, value)
for key, value in parse_qsl(parts.query, keep_blank_values=True)
if not key.startswith("utm_") and key not in tracking_keys
]
return parts._replace(query=urlencode(kept), fragment="").geturl()
print(remove_tracking(url))
print(remove_tracking("https://www.youtube.com/watch?v=jNQXAC9IVRw&feature=youtu.be"))
https://www.example.com/news/2022/how-votes-are-counted
https://www.youtube.com/watch?v=jNQXAC9IVRw
Both results are correct.
The function writes the remaining parameters again, so their encoding can change in small ways: a space that was written as %20 becomes +.
This rule has the opposite weakness.
It keeps every tracking parameter that is not in the set.
To find them, count the keys in your own data.
The next cell counts the keys in the field url of the Reddit file.
from collections import Counter
has_query = df["url"].apply(lambda url: urlsplit(url).query != "")
print(has_query.sum(), "of", len(df), "links have a query")
key_counts = Counter(
key
for url in df["url"]
for key, value in parse_qsl(urlsplit(url).query, keep_blank_values=True)
)
pd.DataFrame(key_counts.most_common(10), columns=["key", "links"])
219 of the 1,832 links have a query. The table lists the ten most frequent keys.
utm_source,utm_medium, andutm_campaignare tracking parameters.featureis the YouTube parameter from above.vis the ID of a YouTube video. It must stay.feed_idand_unique_idare the most frequent keys, with 112 links each. Their names do not say what they do.
For an unknown key, compare the links with the key to the same links without their query.
with_id = df.loc[df["url"].str.contains("_unique_id="), "url"].drop_duplicates()
without_query = with_id.apply(strip_query)
print(len(with_id), "distinct links with the key _unique_id")
print(without_query.nunique(), "distinct links after strip_query")
most_frequent = without_query.value_counts().index[0]
with_id[without_query == most_frequent].tolist()
The 112 links are all different, and they are only 70 different addresses without the query.
The cell also prints the links of the address that appears most often.
Their path names one article, and they differ only in the values of feed_id and _unique_id.
The two keys do not select the page, so they can be removed.
The same test on the YouTube links gives the opposite answer: every path is /watch, and only the parameter v separates the videos.
The counts alone do not separate the two cases.
You have to read some links.
The next cell adds the two keys to the set and cleans every link. It then counts the distinct links under three rules.
tracking_keys.update(["feed_id", "_unique_id"])
df["clean_url"] = df["url"].apply(remove_tracking)
print(df["url"].nunique(), "distinct links as they are in the file")
print(df["clean_url"].nunique(), "distinct links after remove_tracking")
print(df["url"].apply(strip_query).nunique(), "distinct links after strip_query")
The 1,832 submissions hold 1,281 distinct links.
remove_tracking leaves 1,237 distinct links: it merges the links that differ only in a tracking parameter.
strip_query leaves 1,212.
Some of its extra merges are errors, because it also merges different YouTube videos.
No rule is right for every website. Report the rule that you used.
Extract the domain¶
Most analyses describe the website of a link, and not the single page.
The name of the website is the domain, such as nytimes.com.
The netloc is not the domain yet.
It can start with a subdomain, such as www. or news..
Taking the last two parts of the name does not work, because the ending of a domain can have two parts.
for netloc in ["www.nytimes.com", "news.bbc.co.uk"]:
print(netloc.split(".")[-2:])
['nytimes', 'com']
['co', 'uk']
The second result should be bbc.co.uk.
tldextract solves this with the Public Suffix List, a public list of all endings under which people can register a domain, such as com, org, and co.uk.
It splits a URL into the subdomain, the domain, and the suffix.
import tldextract
e = tldextract.extract("https://www.nytimes.com/section/politics")
print((e.subdomain, e.domain, e.suffix))
e = tldextract.extract("https://news.bbc.co.uk/2/hi/uk_news")
print((e.subdomain, e.domain, e.suffix))
('www', 'nytimes', 'com')
('news', 'bbc', 'co.uk')
The first call of tldextract downloads the current Public Suffix List and saves it on the machine.
If the download fails, the package uses the copy of the list that it was installed with.
get_domain joins the domain and the suffix.
This is called the registered domain.
The function lowercases the result, because NYTimes.com and nytimes.com are the same website.
It returns None when the URL has no domain.
def get_domain(url):
"""Return the registered domain of a URL in lowercase, or None if it has none."""
e = tldextract.extract(url)
if not e.domain or not e.suffix:
return None
return f"{e.domain}.{e.suffix}".lower()
for url in [
"https://WWW.NYTimes.com/section/politics",
"https://news.bbc.co.uk/2/hi/uk_news",
"https://youtu.be/jNQXAC9IVRw",
"https://example.github.io/project/",
"/r/AskReddit/comments/abc123/",
]:
print(get_domain(url), "<-", url)
nytimes.com <- https://WWW.NYTimes.com/section/politics
bbc.co.uk <- https://news.bbc.co.uk/2/hi/uk_news
youtu.be <- https://youtu.be/jNQXAC9IVRw
github.io <- https://example.github.io/project/
None <- /r/AskReddit/comments/abc123/
The function makes one decision for you: it drops the subdomain.
This is right for www.nytimes.com, and it is the usual choice for news sites.
It is wrong for a hosting service.
Every website on GitHub Pages has an address of the form name.github.io, and the function returns github.io for all of them.
tldextract.TLDExtract(include_psl_private_domains=True) builds an extractor that treats github.io as a suffix, so that example.github.io is the domain.
Decide whether to keep the subdomain before you count, and report the choice.
The last URL has no domain. It is a relative address, which is valid only inside one website.
The next cell extracts the domain of every cleaned link of the Reddit file.
df["domain"] = df["clean_url"].apply(get_domain)
on_reddit = df["domain"].isin(["reddit.com", "redd.it"])
print(df["domain"].isna().sum(), "links have no domain")
print(on_reddit.sum(), "links stay on Reddit")
33 links have no domain: 30 are relative addresses of other Reddit posts, and 3 are empty.
654 links stay on Reddit.
They are addresses of posts on reddit.com, and of images and videos that were uploaded to Reddit, which are on redd.it.
The other links go to other websites. The rest of the notebook works with these links.
outside = df[df["domain"].notna() & ~on_reddit].copy()
print(len(outside), "links to other websites")
print(outside["clean_url"].nunique(), "distinct links")
print(outside["domain"].nunique(), "distinct domains")
Count domains¶
The simplest description of the links is the number of links for each domain.
outside["domain"].value_counts().head(10)
The 1,145 links are 575 distinct links, and they go to 210 domains.
google.com is first with 298 links, followed by twitter.com (77), foxnews.com (54), and cnn.com (35).
Do not report this ranking as it is. It has three problems.
One website has two domains.
youtu.be (31 links) and youtube.com (27 links) are the same website.
The section "Expand shortened links" showed that a youtu.be link leads to youtube.com.
When a shortening service belongs to one website, a small dictionary of aliases replaces the requests.
aliases = {"youtu.be": "youtube.com"}
outside["domain"] = outside["domain"].replace(aliases)
A link count does not say how many people shared the domain. One community can post the same link many times. The next cell counts three numbers for each domain: the links, the distinct links, and the distinct subreddits that posted them.
domain_table = (
outside.groupby("domain")
.agg(
links=("clean_url", "size"),
distinct_links=("clean_url", "nunique"),
subreddits=("subreddit", "nunique"),
)
.sort_values("links", ascending=False)
)
domain_table.head(10)
The 298 links to google.com are 25 distinct links from 3 subreddits.
The 35 links to cnn.com are 11 distinct links from 19 subreddits.
youtube.com now has 58 links from 44 subreddits.
All posts on user profiles count as one subreddit here.
Sorting by the number of subreddits gives another ranking.
domain_table.sort_values("subreddits", ascending=False).head(10)
youtube.com and cnn.com are now at the top, and google.com is not among the first ten.
Which ranking is right depends on the question.
The number of links measures volume, and a few very active accounts can produce most of it.
The number of communities measures how widely a domain is shared.
The domain is not always the publisher.
The next cell shows how the paths of the google.com links start.
google = outside.loc[outside["domain"] == "google.com", "clean_url"]
google.str.split("/").str[3:6].str.join("/").value_counts()
Almost all of these links start with google.com/amp/s/sites.google.com.
A link of this form shows a page of another website through Google, and the address of that page follows after /amp/s/.
Here the page is on sites.google.com, a service where anyone can build a website.
The registered domain is google.com in both forms.
A domain says who owns the address.
On a hosting service, on a social media platform, and in a link of this form, it does not say who wrote the content.
A link to twitter.com has the same limit, and it has one more property: its path contains the name of an account.
The cell that loads the file replaced these names with the word account.
In your own data, a table of full links can contain account names, and a table of domains cannot.
Join to a domain list¶
A domain name alone says little. Public lists describe domains: what kind of website a domain is, how reliable it is, and who shares it. To use a list, join it to your table of domains.
A list of news domains¶
The list of news domains holds U.S. news domains that were compiled from several existing datasets.
The file has one column, domain.
The next cell downloads it (0.4 MB) from a fixed commit of its repository.
news_url = (
"https://raw.githubusercontent.com/yang3kc/list_of_news_domains/"
"7c88993aa83687ca36885529d10c62ac30a00021/"
"data/output/news_domains.csv"
)
news_path = pathlib.Path("data") / "news_domains.csv"
if not news_path.exists():
urllib.request.urlretrieve(news_url, news_path)
news = pd.read_csv(news_path)
print(news.shape)
news.head()
The list has 23,516 domains.
With one column, the join is a membership test: isin marks the domains of the table that are on the list.
news_domains = set(news["domain"])
domain_table["is_news"] = domain_table.index.isin(news_domains)
print(domain_table["is_news"].sum(), "of", len(domain_table), "domains are on the news list")
print(domain_table.loc[domain_table["is_news"], "links"].sum(), "of", domain_table["links"].sum(), "links go to these domains")
121 of the 209 domains are on the list, and 509 of the 1,145 links go to them, which is 44%.
A join matches two values only if they are written in exactly the same way.
get_domain returns a lowercase registered domain without www., and most entries of the list have this form.
The list also has entries with a subdomain, and a table of registered domains never matches them.
Check the form of the key in every list before you join.
A list covers only what its authors collected. Look at the most frequent domains that did not match.
domain_table[~domain_table["is_news"]].head(10)
The first three rows are google.com, twitter.com, and youtube.com, which are not news sites.
The other rows are small websites that the list does not know.
"Not on the list" does not mean "not news".
This list covers U.S. news domains, and it can miss a new site, a small site, and a site from another country.
Easy types¶
Two types of domains need no list of thousands of entries.
Social media platforms are few, so a short hand-written set covers them.
U.S. government, education, and military sites end with .gov, .edu, and .mil.
domain_type checks these two rules first and then the news list.
platforms = {
"twitter.com", "x.com", "youtube.com", "facebook.com", "instagram.com",
"tiktok.com", "reddit.com", "twitch.tv", "t.me",
}
def domain_type(domain):
if domain in platforms:
return "social media"
if domain.endswith((".gov", ".edu", ".mil")):
return "government or education"
if domain in news_domains:
return "news"
return "other"
domain_table["type"] = [domain_type(domain) for domain in domain_table.index]
domain_table.groupby("type").agg(domains=("links", "size"), links=("links", "sum"))
Among the link posts, 509 links go to news domains, 140 go to social media platforms, and 1 goes to a government or education site.
The other 495 links are of the type other, and 298 of them are the google.com links from above.
The links that were extracted from the text of the posts are different.
text_domains = all_text_urls.apply(get_domain).dropna().replace(aliases)
text_domains.apply(domain_type).value_counts()
113 of the 1,289 links in the text go to a government or education site, against 1 of the 1,145 link posts.
Most of these links go to websites of U.S. states and counties, such as virginia.gov.
Where the links come from changes the result, so say which links you counted.
The rules are simple, and they have limits.
The set of platforms is short and hand-written.
The endings .gov, .edu, and .mil are those of the United States.
Other countries use other forms, such as .gov.uk and .ac.uk.
For the type other, there are lookup services that return a category for a domain, and the last option is to label the most frequent domains by hand.
Audience metrics from DomainDemo¶
DomainDemo (Yang et al., 2025) describes who shares a domain. Its authors matched more than 1.5 million Twitter accounts to U.S. voter records. For each domain that these users shared between 2011 and 2022, they compared the users who shared it with all users of the panel.
The repository has six public files with one metric each. This notebook uses two of them.
- Localness, in
derived_state_kl.csv.gz. The value is 0 when the users who share the domain are spread over the U.S. states in the same way as all users. It is larger when they are concentrated in a few states. - Audience partisanship, in
derived_party_leaning.csv.gz. The value goes from -1 to 1. A negative value means that Democrats share the domain more than Republicans, and a positive value means the opposite.
The other four files hold the same kind of metric for age, race, gender, and party registration. The next cell downloads the two files (about 2 MB each) from a fixed commit and puts them into one table.
demo_base = (
"https://raw.githubusercontent.com/LazerLab/DomainDemo/"
"a2a834400ad582d1c8a5150338a146f2af2a95b0/"
"data/derived_metrics/"
)
metric_files = {
"localness": "derived_state_kl.csv.gz",
"party_leaning": "derived_party_leaning.csv.gz",
}
metrics = []
for name, file_name in metric_files.items():
path = pathlib.Path("data") / file_name
if not path.exists():
urllib.request.urlretrieve(demo_base + file_name, path)
metric = pd.read_csv(path).set_index("domain")
metric.columns = [name]
metrics.append(metric)
scores = pd.concat(metrics, axis=1)
print(scores.shape)
scores.loc[["cnn.com", "news9.com", "wickedlocal.com", "msnbc.com", "breitbart.com"]].round(3)
The table has 129,127 domains. The cell prints the scores of five of them.
cnn.comhas a localness of 0.013. People in all states share it.news9.comandwickedlocal.comare local news sites in Oklahoma City and in Boston. Their localness is above 2.msnbc.comhas a negative audience partisanship (-0.411), andbreitbart.comhas a positive one (0.302).
The join uses the domain as the key again.
how="left" keeps every domain of the Reddit table, also when DomainDemo has no score for it.
domain_table = domain_table.join(scores, how="left")
has_score = domain_table["localness"].notna()
print(has_score.sum(), "of", len(domain_table), "domains have a score")
print(domain_table.loc[has_score, "links"].sum(), "of", domain_table["links"].sum(), "links go to these domains")
domain_table.head(10).round(3)
154 of the 209 domains have a score, and 989 of the 1,145 links go to them, which is 86%.
All 121 news domains have a score.
A domain without a score has NaN in the two new columns.
DomainDemo includes only the domains that at least 50 users of its panel shared, so small and new websites are missing.
Report the coverage of every join: how many domains matched, and how many links they stand for.
Two limits apply to every result from these scores.
- The scores describe the Twitter users who shared a domain between 2011 and 2022. They do not describe the Reddit users in this file.
- The scores describe an audience. They do not describe the content of the website.
From scores to categories¶
Many analyses need a category and not a score: is a news domain local or national, and is its audience more Democratic or more Republican? A rule with a cutoff turns a score into a category, and you choose the cutoff.
- Audience partisanship has a natural candidate, 0: below 0, Democrats share the domain more, and above 0, Republicans do.
- Localness has no natural cutoff. The authors of DomainDemo compared the score with existing lists that label news domains as local or national. They report that a cutoff of 0.243 gives the best agreement with these lists.
The cutoff for localness was chosen on news domains, so the next cell applies it to the news domains only.
news_table = domain_table[domain_table["is_news"] & has_score].copy()
news_table["scope"] = (news_table["localness"] > 0.243).map({True: "local", False: "national"})
news_table["audience"] = (news_table["party_leaning"] > 0).map(
{True: "more Republican", False: "more Democratic"}
)
pd.crosstab(news_table["scope"], news_table["audience"], margins=True)
The table counts domains. Of the 121 news domains, 30 are local and 91 are national, and 101 have a more Democratic audience and 20 a more Republican one.
A count of domains gives every domain the same weight. The next cell sums the links.
news_table.groupby(["scope", "audience"])["links"].sum().unstack()
Of the 509 links to news domains, 66 go to local domains and 443 go to national ones, and 400 go to domains with a more Democratic audience and 109 to domains with a more Republican one. The share of local domains is 25% (30 of 121), and the share of links to local domains is 13% (66 of 509). Both numbers are correct, and they answer different questions. Say which one you report.
The cutoff changes the result¶
The next cell counts the local domains for four cutoffs.
cutoffs = [0.1, 0.243, 0.5, 1.0]
pd.DataFrame({
"local domains": [(news_table["localness"] > cutoff).sum() for cutoff in cutoffs],
"links to them": [news_table.loc[news_table["localness"] > cutoff, "links"].sum() for cutoff in cutoffs],
}, index=pd.Index(cutoffs, name="cutoff"))
The number of local domains goes from 55 with a cutoff of 0.1 to 6 with a cutoff of 1.0. A report must state the cutoff and where it comes from.
A cutoff that comes from a paper was chosen on the data of that paper. Read the rows near the cutoff before you use it on your own data. The next cell lists the ten local domains with the lowest localness.
news_table[news_table["scope"] == "local"].sort_values("localness")[["links", "localness", "party_leaning"]].head(10).round(3)
Four of these ten rows are news sites from other countries: France, Germany, and the Philippines. A foreign news site is not a local U.S. news site. A high localness says only that the panel users who share the domain are concentrated in a few states. The cutoff was chosen on lists of U.S. news domains, and it does not fit these rows. For this file, a better rule first removes the news domains that are not from the United States.
The cutoff of 0 for the audience partisanship has a similar problem. The next cell counts the news domains with a score near 0.
near_zero = news_table["party_leaning"].abs() <= 0.1
print(near_zero.sum(), "of", len(news_table), "news domains have a score between -0.1 and 0.1")
19 of the 121 news domains have a score between -0.1 and 0.1. The cutoff of 0 gives a domain with a score of -0.01 the same label as a domain with a score of -0.5. The authors of DomainDemo also note that the score is relative, so 0 does not have to mean a politically neutral audience. Two options are a third category for the scores near 0, and an analysis that uses the score itself.
The plot shows both scores of the 121 news domains with the two cutoffs. The size of a point grows with the number of links.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5, 3.5))
ax.scatter(
news_table["party_leaning"],
news_table["localness"],
s=8 + 4 * news_table["links"],
alpha=0.5,
linewidths=0,
)
ax.axvline(0, color="gray", linestyle="--", linewidth=1)
ax.axhline(0.243, color="gray", linestyle="--", linewidth=1)
ax.set_yscale("log")
ax.set_xlabel("Audience partisanship (negative: more Democratic)")
ax.set_ylabel("Localness (log scale)")
ax.spines[["top", "right"]].set_visible(False)
plt.show()
On the localness axis, the points do not form two separate groups. Many domains are close to the horizontal dashed line, and a small change of the cutoff moves them to the other category.
A category from a cutoff is a measurement, and it can be wrong. Before you rely on it, label a sample of your own domains by hand and compare your labels with the categories.
What to report¶
- How you found the links: a field of the platform, or extraction from text.
- Whether you expanded shortened links, and how many requests failed.
- Which query parameters you removed.
- Whether you kept the subdomain, and which aliases you used.
- The name and the version of every domain list, and the coverage of every join.
- Every cutoff and its source.