Charset in Web Scraping: How to Detect Page Encoding and Get Rid of Mojibake
Table of contents
- Introduction: why you need to understand charset before scraping
- Prerequisites: tools and environment
- Core concepts: encoding, charset, unicode, and mojibake in plain english
- Step 1: read charset from the http content-type header
- Step 2: find charset inside the document—meta, bom, and xml declaration
- Step 3: decode correctly—content vs text, strict mode, and auto-detection
- Step 4: diagnose mojibake by its appearance and fix it
- Step 5: save scraped data without loss
- Step 6: build a universal decoding function
- Verify the result: checklist and testing
- Common mistakes and solutions
- Advanced features and settings
- Faq: common questions about charset in web scraping
- Conclusion
Introduction: Why You Need to Understand Charset Before Scraping
If you've ever scraped websites, you've probably seen garbled text instead of clean readable content—something like "Привет" or "Ïðèâåò" where Russian or other non-Latin text should be. This is called "mojibake," and the cause is almost always the same: you got the charset wrong, meaning you didn't correctly identify the encoding the server used to send the page. This guide is entirely about how to read charset from the HTTP Content-Type header, from the meta tag in HTML, and from other sources, how to decode the response correctly, and how to avoid corrupting data when saving it.
What you'll get out of this. After working through all the steps, you'll have a working Python function that takes any HTTP response, determines its encoding using a clear priority-based algorithm, and returns clean text. You'll learn to recognize what went wrong just by looking at the mojibake, and fix it in under a minute. You'll also learn to save scraped data correctly to CSV, JSON, and databases so it opens in Excel and other programs without distortion.
Who this guide is for. It's written for anyone who collects data from websites and APIs: beginner scraper developers, analysts, marketers writing small scripts, and anyone who's run into encoding issues but doesn't fully understand what's happening under the hood. Advanced topics (BOM, double encoding, Unicode normalization) are covered in separate sections you can skip on your first read.
What you need to know beforehand. Basic Python—enough to write a function and call a library. A general idea of what an HTTP request and response are. If you know that a response has headers and a body, that's enough. Everything else is explained along the way.
How long it'll take. Reading and completing all the steps will take about an hour or an hour and a half. If you test each step on your own real sites as you go, budget two hours. The payoff is worth it: getting charset right saves you hours of debugging down the road.
Prerequisites: Tools and Environment
You'll need a minimal set of tools for this guide. Nothing exotic—everything is free and installs in minutes.
Required Tools
- Python (a current version). Any modern Python 3 release will work. Check that
python --versionorpython3 --versionin your terminal prints a version number. - The requests library for HTTP requests. Install it with
pip install requests. - The charset-normalizer library for automatic encoding detection. It comes bundled with requests, but just in case, run
pip install charset-normalizer. - The beautifulsoup4 and lxml libraries for HTML parsing:
pip install beautifulsoup4 lxml. - curl—a command-line utility for inspecting headers. It's built into Windows, macOS, and Linux by default.
- Any browser with developer tools. Chrome, Firefox, Edge—any will do.
- A text editor that can display and change file encoding: VS Code, Notepad++, Sublime Text.
System Requirements
Any computer that runs Python. The operating system doesn't matter: the examples work the same on Windows, macOS, and Linux. The only place where there's a difference is the Windows console, which may not use UTF-8 by default—we'll cover that in the errors section.
What to Set Up Before You Start
- Create a separate folder for experiments, for example
charset-lab. - Open a terminal in that folder.
- Create a virtual environment with
python -m venv venvand activate it. On Windows:venv\Scripts\activate; on macOS and Linux:source venv/bin/activate. - Install the libraries in one command:
pip install requests charset-normalizer beautifulsoup4 lxml. - In your editor settings, make sure new files are created in UTF-8 without BOM. In VS Code that's the
files.encodingsetting, which defaults toutf8.
Tip: If you use proxies for scraping—mobile or residential proxies, for example—configure them in requests via the proxies parameter before you start testing encodings. A proxy doesn't change the response charset, but it's important that your test environment matches production.
Backups
If you're going to re-encode already-collected data files, always back up the originals. Re-encoding is an operation that irreversibly corrupts data if something goes wrong. Simple rule: don't touch the original, write the result to a new file, compare, and only then delete the old one.
Core Concepts: Encoding, Charset, Unicode, and Mojibake in Plain English
Before we get to the steps, let's agree on terminology. There isn't much of it, but without it the rest of this charset tutorial won't make sense.
Bytes and Text Are Different Things
Computers store and transmit only bytes—numbers from zero to two hundred fifty-five. A letter "A" isn't a byte by itself. To turn a letter into bytes, you need an encoding—a table that maps characters to bytes. The reverse process is called decoding. When you receive an HTTP response, you receive bytes. To see text, you need to decode them, and for that you need to know which table the server used.
What Is Charset
Charset literally means "character set," but in practice it's used as a synonym for encoding. When a server writes Content-Type: text/html; charset=utf-8 in the header, it's saying: "I encoded this body in UTF-8, decode it the same way." It's a hint, not a guarantee. The server can be wrong, and then you get mojibake even when faithfully following the header.
The Main Encodings You'll Encounter
- UTF-8—the universal Unicode encoding and the standard of the modern web. One Cyrillic letter takes two bytes, Latin takes one. If you have a choice, always pick UTF-8.
- windows-1251 (also cp1251)—an old single-byte encoding for Cyrillic, still found on Russian sites built long ago. Each letter is exactly one byte.
- KOI8-R—an even older encoding, rarely seen but occasionally found on archival resources and email systems.
- ISO-8859-1 (latin-1)—a Western European encoding. It's important to know because some tools default to it when charset isn't specified, and that's exactly how you get "Ïðèâåò".
Where the Server Can Report Charset
There are several places, and they have different priorities. Remember this order—you'll need it in the next steps:
- BOM—special bytes at the very beginning of the response body, the byte order mark. If present, browsers trust it above everything else.
- The HTTP Content-Type header with a charset parameter.
- The meta tag in HTML:
<meta charset='utf-8'>or the old form<meta http-equiv='Content-Type' content='text/html; charset=windows-1251'>. - The XML declaration:
<?xml version='1.0' encoding='utf-8'?>for XML and RSS. - Auto-detection based on content when none of the above is present.
What Mojibake Is
Mojibake is text decoded with the wrong table. The bytes aren't corrupted—you just read them incorrectly. That's good news: if you saved the original bytes, the error can always be fixed. The bad news is that if you already saved the mojibake as UTF-8 text and threw away the original, recovery is harder, though often still possible.
Important to understand: question marks and diamonds with question marks inside aren't mojibake—they're a sign that characters were lost during decoding. Those can't be recovered; you need to re-request the data.
Step 1: Read Charset from the HTTP Content-Type Header
Goal of this step: learn to see what the server claims about the encoding at the HTTP level, and extract that value in code.
Inspect Headers in the Browser
- Open the site you're interested in in your browser.
- Press F12 to open developer tools.
- Go to the Network tab.
- Refresh the page with F5 so the request list fills up.
- Click the very first request—usually it's the document with the domain name or page path. Its Type will be
document. - In the right panel, open the Headers tab and scroll down to Response Headers.
- Find the
content-typeline. You'll see something liketext/html; charset=UTF-8or justtext/html.
If there's a charset= after the semicolon, you've found the declared encoding. If the parameter is missing, the server said nothing and you'll need to look further in the next step.
Inspect Headers with curl
The browser is convenient, but your scraper works without one, so it's worth checking what the server sends to a script. Run this in your terminal:
curl -I -A "Mozilla/5.0" https://example.com/The -I flag requests headers only. The -A flag sets the User-Agent because some sites serve different responses to different clients. In the output, look for the line starting with content-type. Header name case doesn't matter.
Tip: Some servers respond differently to a HEAD request than to GET, or don't respond at all. If -I doesn't work, use curl -s -D - -o /dev/null https://example.com/—this does a regular GET, prints headers, and discards the body.
Extract Charset in Python
Now let's do the same thing programmatically. Create a file called step1.py:
import requests
url = 'https://example.com/'
headers = {'User-Agent': 'Mozilla/5.0'}
r = requests.get(url, headers=headers, timeout=30)
content_type = r.headers.get('Content-Type', '')
print('Content-Type:', content_type)
charset = None
for part in content_type.split(';'):
part = part.strip()
if part.lower().startswith('charset='):
charset = part.split('=', 1)[1].strip().strip('"').strip("'").lower()
print('charset из заголовка:', charset)
print('requests.encoding:', r.encoding)Run the script. You'll see three lines: the full header, the extracted charset value (or None), and what the requests library itself decided about the encoding.
Important: look at that last line. If the server sent text/html without charset, requests, following the old HTTP rule, will put ISO-8859-1 into r.encoding. That's the classic trap: you call r.text, get "Ïðèâåò", and don't understand why. Remember: r.encoding from the header is only the first candidate, not the final answer.
What Different Header Variants Look Like
text/html; charset=utf-8—all good, encoding is explicit.text/html; charset="windows-1251"—value is in quotes, which need to be stripped. Our code handles that.text/html;charset=UTF-8—no space, uppercase. We lowercase it.text/html—no charset, move to step two.application/json—for JSON, charset is usually omitted because the spec mandates UTF-8. More on this in the advanced section.
Check: the script prints the charset value for a site that has the header, and None for a site without it. If for a site without charset you see requests.encoding: ISO-8859-1, you've reproduced the trap and now understand where Latin mojibake comes from.
Possible Problems
- Header empty or missing. Happens with misconfigured servers. Treat charset as unknown and move on.
- Response is not 200. Error pages are often served in a different encoding than the main site. Check
r.status_codebefore analyzing the encoding. - Redirects. The final page's encoding may differ from the intermediate one. Analyze
r.headersof the final response, notr.history.
Step 2: Find Charset Inside the Document—Meta, BOM, and XML Declaration
Goal of this step: when the header is silent or questionable, find the declared encoding inside the response body and establish the correct priority order.
Check for BOM
BOM is a few special bytes at the very start of the file. For UTF-8 it's three bytes, in hex EF BB BF. Browsers trust BOM more than the header. In Python it's easy to check using the built-in constants from the codecs module, so you don't have to write bytes manually:
import codecs
raw = r.content
bom_charset = None
if raw.startswith(codecs.BOM_UTF8):
bom_charset = 'utf-8-sig'
elif raw.startswith(codecs.BOM_UTF16_LE) or raw.startswith(codecs.BOM_UTF16_BE):
bom_charset = 'utf-16'
print('BOM:', bom_charset)Notice the name utf-8-sig. It's not a separate encoding but a Python decoder mode that automatically strips the BOM. If you decode such a body with plain utf-8, an invisible character will remain at the start of the text, breaking string comparisons and JSON parsing later.
Look for the meta Tag in HTML
If there's no BOM, look for meta in the first few kilobytes of the document. Per the HTML spec, meta charset should be at the very beginning, inside head, so there's no need to parse the whole document. A simple and reliable way is a regex over bytes:
import re
head = raw[:4096]
meta_charset = None
m = re.search(rb'<meta[^>]+charset=["']?\s*([a-zA-Z0-9_-]+)', head, re.I)
if m:
meta_charset = m.group(1).decode('ascii', errors='ignore').lower()
print('charset из meta:', meta_charset)This expression catches both forms: the modern <meta charset='utf-8'> and the old <meta http-equiv='Content-Type' content='text/html; charset=windows-1251'>, because in both cases the tag contains the substring charset=. We search bytes rather than a string because we don't know the encoding yet, and encoding names are always written in Latin characters, which are the same in almost all tables.
Look for the XML Declaration
For RSS feeds, sitemaps, and SOAP responses, the encoding is specified in the first line of the document. Add one more check:
xml_charset = None
m = re.search(rb'<\?xml[^>]+encoding=["']([a-zA-Z0-9_-]+)', head, re.I)
if m:
xml_charset = m.group(1).decode('ascii', errors='ignore').lower()
print('charset из XML:', xml_charset)Establish Priorities
Now you may have up to four candidates: BOM, header, meta, XML. How to choose? Here's the rule that matches browser behavior and common sense:
- If there's BOM—use it, ignore the rest.
- Otherwise, if the HTTP header has charset—use it.
- Otherwise, if there's meta or an XML declaration—use it.
- Otherwise—move to auto-detection (step three).
Note: The header and meta often contradict each other. Typical story: the site was migrated to UTF-8 and the server was reconfigured, but the template still has an old meta with windows-1251. Per the spec, the header wins, and browsers follow it. But in practice the reverse happens too: the server defaults to one charset while a specific page was generated in another. That's why in step three we'll add validation: try to decode strictly with the chosen encoding, and if we get an error, move to the next candidate.
Tip: Normalize every found name to a canonical form. cp1251, windows-1251, win-1251—same table, but Python doesn't know all synonyms. Set up a small alias dictionary: {'win-1251': 'windows-1251', 'cp-1251': 'windows-1251', 'utf8': 'utf-8', 'koi8r': 'koi8-r'} and run every found value through it.
Check: Run the script on three different sites: a modern one (expect utf-8 in both header and meta), an old one with windows-1251, and an RSS feed. In each case the script should print which source the encoding came from. If you see a discrepancy between header and meta, note that site—you'll check which one is right in the next step.
Possible Problems
- Meta found but it's commented out. The regex doesn't see that. Rare, fixable by checking for
<!--right before the tag. - Meta is far from the start. Increase the search window from four kilobytes to sixteen. Usually you won't need more.
- Encoding name Python doesn't know. For example,
x-user-definedor a typo. HandleLookupErrorand fall back to auto-detection.
Step 3: Decode Correctly—content vs text, Strict Mode, and Auto-Detection
Goal of this step: turn bytes into text so the declared encoding is validated, and auto-detection kicks in when it's missing or fails.
The Golden Rule: Work with Bytes
In requests there are two fields: r.content—raw bytes, and r.text—bytes decoded per r.encoding. The problem is that r.encoding is taken only from the header, and when it's missing, ISO-8859-1 is set. Meta is not read by the library. So never use r.text blindly. Take r.content and decode it yourself, or explicitly set r.encoding before accessing r.text.
Strict Decoding as a Check
The Python decoder can work in different modes via the errors parameter. The strict mode (default) throws an exception on the first byte that doesn't fit the table. This is useful: UTF-8 is structured so that random bytes from windows-1251 are almost never valid UTF-8. So successful strict UTF-8 decoding is strong evidence that we really have UTF-8.
def try_decode(raw, encoding):
try:
return raw.decode(encoding)
except (UnicodeDecodeError, LookupError):
return NoneWith single-byte encodings the trick doesn't work: any bytes decode successfully as windows-1251, only the result is meaningless. So they need a second check—for plausibility, covered below.
Auto-Detection with charset-normalizer
When there are no candidates or all failed, plug in the detector. charset-normalizer ships with requests, and you can use it in two ways. First, via requests itself:
print('apparent_encoding:', r.apparent_encoding)The apparent_encoding field runs the detector on the response body and returns its best guess. Second, directly, with access to details:
from charset_normalizer import from_bytes
result = from_bytes(raw).best()
if result is not None:
print('детектор:', result.encoding)
text = str(result)The detector analyzes byte frequencies and compares them to language profiles. On Cyrillic text it usually distinguishes UTF-8, windows-1251, and KOI8-R well because their byte profiles are noticeably different. It's worse on very short texts and on pages that are mostly non-letters—just tags and digits.
Tip: Before auto-detection, cut the contents of script and style tags out of the bytes. They're full of Latin and control characters that confuse the detector. A rough byte regex is enough; precision isn't required.
Plausibility Check for Single-Byte Encodings
If you've decoded as windows-1251 and want to confirm you're right, count the share of letters that look like real words. In real natural text this share is high. Simple heuristic—check for common words like "the", "and", "of". If none are present on a text-heavy page, something is wrong.
def looks_natural(text):
sample = text[:5000].lower()
markers = [' the ', ' and ', ' of ', ' to ', ' is ']
return any(m in sample for m in markers)The heuristic is crude, but for scrapers of English-language sites it filters out the vast majority of errors.
Build Candidates into a Chain
The step-three logic as a sequence:
- Build a list of candidates in priority order from step two: BOM, header, meta or XML.
- Add
utf-8at the end if it's not there yet. UTF-8 is the most common case, and its strict check almost never gives false positives. - Iterate through the list: for each candidate, call
try_decode. For UTF-8, success is sufficient. For single-byte encodings, additionally checklooks_natural. - If no candidate worked, run charset-normalizer and take its answer.
- If even the detector is silent, decode as UTF-8 with
errors='replace'and log a warning. It's the worst case, but it won't crash the scraper.
Check: For the site where header and meta disagreed in step two, the chain should pick the encoding that actually decodes without errors and yields readable text. Print the first two hundred characters of the result. If you see normal words, the step is complete.
Possible Problems
- The detector confidently gives the wrong encoding. Usually this is very short or almost empty pages. In such cases it helps to remember the domain's encoding: if the homepage detected windows-1251, apply it to all pages of the site as the first candidate.
- UTF-8 decoding succeeds but text looks weird. Possible double encoding. Covered in step four.
- LookupError on the encoding name. Run the name through the alias dictionary from step two.
Step 4: Diagnose Mojibake by Its Appearance and Fix It
Goal of this step: learn to instantly figure out from the characteristic characters which pair of encodings got swapped, and to recover text even if the original bytes are already lost.
Mojibake Identifier
Take the reference word and see what it turns into under different errors. This is the most useful reference in the guide—keep it handy.
- "Ðривет"—uppercase Ð and Ñ with tails. UTF-8 bytes read as ISO-8859-1 or windows-1252. This is the most common case when the server didn't send a charset and the library defaulted to Latin.
- "Привет"—Cyrillic Р and С mixed with small symbols. UTF-8 bytes read as windows-1251.
- "Ïðèâåò"—Latin letters with diacritics, lowercase. windows-1251 bytes read as ISO-8859-1. A classic when scraping old sites without charset.
- "ïòé÷åô"—Cyrillic letters, but the word is unreadable, many uppercase in the middle. KOI8-R bytes read as windows-1251 or vice versa. These two tables are "mirror" in case, so lowercase turns into uppercase.
- "??????"—only question marks. The text was decoded correctly but then encoded into a table without the needed letters, with replacement. Data is lost; you need to re-request.
- Diamonds with a question mark inside—the Unicode replacement character. Decoding went with
errors='replace'and hit invalid bytes. The original bytes may still be intact if you saved them.
Fix From Saved Bytes
If you have the original r.content, the cure is trivial: decode with the correct encoding from the identifier above. For example, for the "Ïðèâåò" case:
text = raw.decode('windows-1251')Fix If the Bytes Are Lost
Sometimes the mojibake is already sitting in the database as text. Then we apply the reverse operation: encode the text with the table it was wrongly read as, and decode with the correct one.
broken = 'Ïðèâåò'
fixed = broken.encode('latin-1').decode('windows-1251')
print(fixed)For the "Привет" case:
broken = 'Привет'
fixed = broken.encode('windows-1251').decode('utf-8')
print(fixed)This works because mojibake is a reversible transformation. Each original byte corresponds to exactly one character in the wrong table, and the reverse path restores the bytes precisely.
Warning: The reverse transformation breaks if the mojibake was "normalized" along the way: non-breaking spaces replaced, non-printing characters removed, strip applied, or lowercased. Then part of the bytes won't be restored and you'll get a UnicodeEncodeError. Use errors='replace' at the encode stage to save at least the rest of the text, and make a backup of the table before a bulk fix.
Double Encoding
A separate case is when UTF-8 text is wrongly read as cp1251 and the result is saved again as UTF-8. It looks like "РПРЂ"—mojibake of mojibake. It's fixed in two passes: first restore the first layer, then the second. Sometimes it takes three. Write a loop: while the text contains characteristic sequences like "Ð " or "Ð", apply the reverse transformation—but no more than five iterations to avoid an infinite loop.
Tip: Add a small mojibake-detector function to your project that searches the text for substrings like "Ã", "Ð", "Ñ", "Рџ", "Р°", "С‚". If they appear more often than once per few hundred characters of normal text, flag the record as suspicious. Such a detector catches problems at input, not a week later when a client opens the report.
Check: Take the string "Hello, world", simulate each error from the identifier via encode in one encoding and decode in another, inspect the result, and recover it back. If you can reproduce and fix all six cases, you'll never be stumped by mojibake again.
Step 5: Save Scraped Data Without Loss
Goal of this step: write correctly decoded text to files and databases so it doesn't get corrupted on save and opens in other programs.
Text Files
Always specify the encoding explicitly when opening a file. Without the encoding parameter, Python uses the system encoding—and on Windows that can be cp1251, and once again you get mojibake even though scraping went perfectly.
with open('page.txt', 'w', encoding='utf-8') as f:
f.write(text)If you need to save the original bytes so you can redefine encoding later, open the file in binary mode 'wb' and write raw. That's good practice for a raw archive: bytes don't lie, and you can get text from them at any moment.
CSV for Excel
Excel on Windows opens CSV in the system encoding, and it'll show UTF-8 without BOM as mojibake. The fix is to write the file in utf-8-sig: Python adds a BOM, Excel sees it and switches to UTF-8.
import csv
with open('data.csv', 'w', encoding='utf-8-sig', newline='') as f:
writer = csv.writer(f, delimiter=';')
writer.writerow(['Name', 'Price'])
writer.writerow(['Example', '100'])The newline='' parameter is required by the csv module to avoid duplicating line breaks on Windows. The semicolon delimiter is used because the Russian-locale Excel expects exactly that.
JSON
By default json.dump escapes all non-ASCII characters as sequences like \u041f. That's correct but unreadable and doubles the file size. Turn off escaping:
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(items, f, ensure_ascii=False, indent=2)Database
For MySQL and MariaDB, specify charset directly in connection parameters and use utf8mb4, not utf8: the old utf8 table in MySQL doesn't store emoji and rare characters. For PostgreSQL, check that the database was created with UTF8. For SQLite nothing needs to be configured—it always stores UTF-8.
Warning: If your database or table was created in cp1251, don't try to "reconcile" it with UTF-8 by re-encoding on the fly. That's a source of endless bugs. Create a new table in utf8mb4, migrate data with explicit decoding, verify, and switch. Don't delete the old table until you're sure everything migrated.
Console Output
On Windows, the console may use an outdated encoding, and print with non-ASCII text will either show mojibake or crash. The most reliable way is to enable Python's UTF-8 mode via the PYTHONUTF8=1 environment variable or run chcp 65001 in the terminal before launching the script.
Check: Open the saved CSV in Excel by double-clicking—column headers should be readable. Open JSON in the editor—you should see regular letters instead of \u sequences. Query the database and look at the result in the client—text should match the site.
Step 6: Build a Universal Decoding Function
Goal of this step: combine everything from the previous steps into one function you can plug into any scraper and forget the problem.
Function Code
import re
import codecs
from charset_normalizer import from_bytes
ALIASES = {
'utf8': 'utf-8', 'cp1251': 'windows-1251', 'win-1251': 'windows-1251',
'cp-1251': 'windows-1251', 'koi8r': 'koi8-r', 'latin1': 'iso-8859-1',
}
def normalize_name(name):
if not name:
return None
name = name.strip().strip('"').strip("'").lower()
return ALIASES.get(name, name)
def charset_from_header(content_type):
for part in (content_type or '').split(';'):
part = part.strip()
if part.lower().startswith('charset='):
return normalize_name(part.split('=', 1)[1])
return None
def charset_from_body(raw):
head = raw[:16384]
m = re.search(rb'<meta[^>]+charset=["']?\s*([a-zA-Z0-9_-]+)', head, re.I)
if m:
return normalize_name(m.group(1).decode('ascii', 'ignore'))
m = re.search(rb'<\?xml[^>]+encoding=["']([a-zA-Z0-9_-]+)', head, re.I)
if m:
return normalize_name(m.group(1).decode('ascii', 'ignore'))
return None
def looks_natural(text):
sample = text[:5000].lower()
return any(w in sample for w in [' the ', ' and ', ' of ', ' to ', ' is '])
def decode_response(raw, content_type='', hint=None):
if raw.startswith(codecs.BOM_UTF8):
return raw.decode('utf-8-sig'), 'utf-8-sig', 'bom'
candidates = []
for enc, src in [(charset_from_header(content_type), 'header'),
(charset_from_body(raw), 'meta'),
(hint, 'hint'), ('utf-8', 'default')]:
if enc and enc not in [c[0] for c in candidates]:
candidates.append((enc, src))
for enc, src in candidates:
try:
text = raw.decode(enc)
except (UnicodeDecodeError, LookupError):
continue
if enc == 'utf-8' or looks_natural(text):
return text, enc, src
best = from_bytes(raw).best()
if best is not None:
return str(best), best.encoding, 'detector'
return raw.decode('utf-8', errors='replace'), 'utf-8', 'fallback'How to Use It
- Save the code to a file called
charset_utils.pynext to your scraper. - Import the function:
from charset_utils import decode_response. - After each request, call:
text, enc, src = decode_response(r.content, r.headers.get('Content-Type', '')). - Pass
texton to BeautifulSoup or another parser. - Log
encandsrc. After a week of running the scraper, the log will show which sites are "finicky", and you can pass a hint for them via thehintparameter.
The hint parameter is the encoding you remembered for a domain. If on the homepage the function returned windows-1251 from the detector, pass that value for the rest of the pages: it'll go in the candidate queue before UTF-8 and pass the strict validation.
Tip: If you use BeautifulSoup, you can just pass it bytes: BeautifulSoup(r.content, 'lxml', from_encoding=enc). That way the parser will apply the encoding itself and won't try to guess. But the result from our function is more reliable than BeautifulSoup's built-in guess, so it's better to hint the encoding explicitly.
Check: Run the function on a list of a dozen different sites: modern, old, RSS feeds, error pages. For each, print the encoding source and the first hundred characters of the text. There should be zero lines with mojibake. If some site still gives garbage, go back to step four and work it out by the identifier.
Verify the Result: Checklist and Testing
Go through the list. Every item should pass—then charset in your scraper is set up correctly.
Checklist
- The scraper never uses
r.textwithout first settingr.encoding, or it usesr.contentwith its own decoding. - The decode function checks BOM, then header, then meta, then auto-detection—in exactly that order.
- Every candidate goes through strict decoding, and an error leads to the next candidate, not a crash.
- Encoding names are normalized via an alias dictionary.
- All files are opened with an explicit
encodingparameter. - CSV for Excel is written in
utf-8-sigwith a semicolon delimiter. - JSON is written with
ensure_ascii=False. - The database uses utf8mb4 or UTF8.
- Logs record which source the encoding came from for each page.
- Raw response bytes are saved at least for debugging so a decoding error can be fixed without re-requesting.
How to Test
- Create a test set from several pages of different types: charset in header, meta only, nothing, BOM, header/meta mismatch, RSS feed, JSON API response.
- Save their raw bytes to binary files so tests don't depend on the network.
- For each file, write down the expected encoding and a fragment of the correct text.
- Write a test that calls
decode_responseand compares the result to the expectation. - Add a test for the reverse mojibake transformation from step four.
Success Metrics
All tests pass. In the production scraper log, the fallback source doesn't appear or appears only on clearly broken pages. The mojibake detector doesn't flag records as suspicious. Files open correctly in Excel, an editor, and a database client.
Common Mistakes and Solutions
Problem: "Ïðèâåò" Instead of Russian Text
Cause: the server didn't send charset, requests defaulted to ISO-8859-1, and the site is in windows-1251. Solution: don't use r.text; decode r.content through the function from step six. To salvage already-saved text: s.encode('latin-1').decode('windows-1251').
Problem: "Привет" in the Database
Cause: UTF-8 text was written through a connection or into a table configured for cp1251. Solution: check the connection and table charset, migrate to utf8mb4. To salvage data: s.encode('windows-1251').decode('utf-8').
Problem: Excel Shows Mojibake in CSV
Cause: the file is UTF-8 without BOM, and Excel reads it in the system encoding. Solution: write the file in utf-8-sig. Alternative—import via the "Data" menu with explicit encoding—but BOM is simpler.
Problem: UnicodeEncodeError on print in Windows
Cause: the console doesn't support UTF-8, and the text has a character not in its encoding. Solution: set the PYTHONUTF8=1 environment variable or run chcp 65001. As a last resort, on output use text.encode('cp866', errors='replace').decode('cp866'), but that's a debugging hack.
Problem: json.loads Fails on the First Character
Cause: there's a BOM at the start of the response, which the JSON parser doesn't expect. Solution: decode as utf-8-sig or strip the BOM manually. The r.json() method in requests usually handles it, but with manual decoding it's a common error.
Problem: Header Says UTF-8, but the Page Is in windows-1251
Cause: the server is configured globally, but a specific section is generated by old code. Solution: strict decoding validation from step three. UTF-8 will fail; the function will move to meta or the detector.
Problem: BeautifulSoup Gives Mojibake Even Though the Bytes Are Fine
Cause: you passed BeautifulSoup a string that was already decoded incorrectly, or you passed bytes without a hint and its built-in detector guessed wrong. Solution: pass the text from decode_response, or pass bytes with the from_encoding parameter.
Problem: Text Looks Correct, but String Comparison Doesn't Work
Cause: characters that look the same are written differently: for example, an accented letter as one character vs. the base letter plus a combining mark. This is a Unicode normalization problem. Solution: normalize the text to NFC form via unicodedata.normalize('NFC', text) right after decoding.
Problem: Mojibake Only on Some Pages of a Site
Cause: different pages are served by different backends or cache with different settings. Solution: don't cache the domain encoding as the single truth—use it only as a hint, which still passes strict validation.
Advanced Features and Settings
Charset in JSON API Responses
The JSON spec mandates UTF-8, so many APIs don't specify charset in Content-Type. That's normal. But some legacy corporate APIs return JSON in windows-1251, and then r.json() fails. Solution: apply decode_response to bytes and then json.loads on the result. Strict UTF-8 validation for JSON is especially reliable because the JSON structure is mostly ASCII, and values in cp1251 will almost certainly violate UTF-8 rules.
Compression and Charset
The Content-Encoding: gzip header has nothing to do with charset—it's compression, not character encoding. requests automatically decompresses the body, and r.content already contains the decompressed bytes. If you work with low-level libraries, first decompress, then determine charset. BOM checks on compressed bytes are meaningless.
Async Clients
In httpx and aiohttp the logic is the same: take bytes, not ready-made text. In httpx that's r.content, in aiohttp—await resp.read(). aiohttp's text() method accepts an encoding parameter into which you can pass the result of your function. In httpx you can override r.encoding before accessing r.text, same as in requests.
Parsing Directly with lxml
If you use lxml without BeautifulSoup, pass bytes and explicitly set the parser encoding: lxml.html.fromstring(raw, parser=lxml.html.HTMLParser(encoding=enc)). If you pass an already decoded string that still contains meta with another charset, lxml may throw an error about conflicting declarations. The simplest approach is to work with bytes and an explicit encoding.
Node.js
The built-in Buffer only supports UTF-8, latin1, and a few other encodings—it doesn't know windows-1251. Use the iconv-lite package: iconv.decode(buffer, 'win1251'). The charset detection logic is the same: header, meta, detector (the jschardet package).
Normalization and Cleanup After Decoding
After successful decoding it makes sense to do three things: normalize the text to NFC, replace non-breaking spaces with regular ones if they aren't needed, and strip null characters that sometimes leak in from corrupted data. Do it after decoding and before saving, but never before attempting to recover mojibake: normalization breaks the reverse transformation.
Encodings and Proxies
A proxy passes bytes through as-is and doesn't change charset. But there's a nuance: some sites serve different page versions, including with different encodings and headers, to different regions. If you collect data through mobile or residential proxies, add pages fetched via the proxy to your test set to make sure the decode function behaves the same. Proxeon recommends logging not only the encoding but also the exit IP so that, when investigating oddities, it's clear where a particular response came from.
Performance Optimization
Auto-detection via charset-normalizer is the most expensive operation in the chain. On large volumes it's noticeable. Two tricks: first, cache the encoding by domain and pass it as a hint, so the detector is almost never invoked; second, pass the detector not the entire document but the first few dozen kilobytes—that's enough for recognizable text.
FAQ: Common Questions About Charset in Web Scraping
What's the difference between charset and encoding?
In practice, nothing. HTTP and HTML use the word charset, XML and Python use encoding. Both refer to the mapping table between characters and bytes.
Why does requests default to ISO-8859-1 if charset isn't specified?
That's what the old version of the HTTP spec said for text types. The modern spec removed that rule, but the library preserves the behavior for compatibility. That's exactly why you can't rely on r.text blindly.
Can I trust charset-normalizer 100%?
No. The detector is a statistical guess. It's good on long texts with plenty of letters and weak on short or nearly empty pages. That's why in our chain it goes last, after explicit declarations and strict validation.
What if chardet and charset-normalizer give different answers?
Check both with strict decoding and a natural-text heuristic. The one that passes validation wins. If both pass, look at the first lines with your own eyes—the difference is usually obvious.
Should I save raw bytes?
Highly recommended, at least for debugging. Bytes let you fix any decoding error without re-requesting. For large volumes you can store only the first few kilobytes of each page.
How do I know if a site is in KOI8-R?
Usually by the header or meta. If neither exists, the detector usually handles it because KOI8-R's frequency profile differs from cp1251. Visual cue: reading KOI8-R as cp1251 turns lowercase letters into uppercase and vice versa.
Why is BOM more important than the header?
Because BOM is inside the file itself, set by whoever saved it, while the header is produced by the web server, which may know nothing about the content. Browsers follow the same priority.
What is utf-8-sig and when should I use it?
It's a Python decoder/encoder mode that strips the BOM on read and adds it on write. Use it when reading any UTF-8 files of unknown origin, and when writing CSV for Excel.
What about encodings in filenames and URLs?
URLs are always percent-encoded based on UTF-8 by modern rules, but old sites can encode parameters in cp1251. If Cyrillic links don't work, try urllib.parse.quote(value, encoding='windows-1251'). Filenames on disk are a separate story; Python usually handles them correctly via system calls.
Can I just always decode as UTF-8 with errors='replace'?
No. You'll silently lose some characters on every site in cp1251 and won't know it until you look at the data. Replace mode is only a last resort, and its occurrence must be logged.
Conclusion
Let's wrap up. You've gone from raw bytes to clean text and back. Now you know how to read charset from the HTTP Content-Type header and from the meta tag in HTML, check BOM, establish priorities between sources, and plug in auto-detection only when explicit declarations are missing or wrong. You've learned to recognize the swapped encoding pair by the look of mojibake and to recover text even without the original bytes. And most importantly, you've built a universal decoding function you can plug into any scraper.
What to do next. Integrate the function into your working project and enable logging of the encoding source. Build a test set from pages that used to cause trouble and make sure they all pass. Verify the data-saving chain: files, CSV, JSON, database—everywhere must be explicit UTF-8. If you've accumulated old tables with mojibake, plan to fix them via the reverse transformation, always with a backup.
Where to go from here. The next level is working with Unicode deeper than encodings: normalization, case-insensitive string comparison for different alphabets, handling emoji and combining characters. It's also worth exploring how encodings behave in PDF, DOCX, and email—there are their own rules. And if you collect data at scale through distributed infrastructure and proxies, your encoding logs become a great source of insight into which sites change behavior based on region and client. Good luck scraping without mojibake.