Draft:Urlib

urllib
DeveloperPython Software Foundation
Written inPython
Operating systemCross-platform
TypeStandard library
LicensePython Software Foundation License
Websitedocs.python.org/3/library/urllib.html

urllib is a package in the Python standard library for working with URLs and making HTTP requests. It provides a collection of submodules for fetching data from the web, parsing URLs, and handling network-related errors. urllib ships with every standard Python 3 installation and requires no additional dependencies.

History

Python's built-in URL handling has evolved considerably across major versions of the language.

Python 1.x and 2.x

The original urllib module was introduced in Python 1.2 (later accounts place it around version 1.4), providing a simple interface for fetching URLs via the urlopen() and urlretrieve() functions. It was a significant step forward from lower-level socket-based programming and made network requests more accessible.

In Python 1.6, a second module, urllib2, was added alongside the original urllib. Despite the name suggesting an incremental upgrade, urllib2 was effectively a brand-new library with a fundamentally different design. It introduced a flexible handler-based architecture, support for HTTP authentication (basic and digest), cookie handling, custom request headers, and redirect processing. urllib2 was the standard choice for more complex HTTP use cases throughout the Python 2.x era.

Python 3

When Python 3 was released in 2008, the original urllib module was deprecated and removed. The functionality of urllib2 was merged and refactored into the new urllib package, split across several submodules. The transition tool 2to3 can assist in converting Python 2 urllib2 code to the Python 3 urllib equivalent, owing to their relative similarity.

Submodules

In Python 3, urllib is organized into four submodules:

urllib.request

urllib.request is the primary submodule for opening and reading URLs. It defines the urlopen() function and the Request class, and supports:

  • HTTP and HTTPS requests (GET, POST, etc.)
  • HTTP authentication (basic and digest)
  • HTTP cookies via http.cookiejar integration
  • Proxy handling via ProxyHandler
  • Redirect following
  • Custom request headers and user-agent strings

Basic usage example:

import urllib.request

with urllib.request.urlopen("https://www.example.com") as response:
    html = response.read()

To send a POST request, a data argument is passed:

import urllib.request
import urllib.parse

data = urllib.parse.urlencode({"key": "value"}).encode()
req = urllib.request.Request("https://www.example.com/post", data=data)
with urllib.request.urlopen(req) as response:
    result = response.read()

urllib.parse

urllib.parse provides functions for parsing and constructing URLs. It conforms to RFC 3986, the current standard for URI syntax.

Key functions include:

Function Description
urlparse() Splits a URL into its components (scheme, netloc, path, params, query, fragment)
urlunparse() Assembles a URL from its components
urlencode() Encodes a dictionary into a URL query string
quote() Percent-encodes special characters in a URL string
unquote() Decodes percent-encoded characters
urljoin() Resolves a relative URL against a base URL

Example:

from urllib.parse import urlparse, urlencode

parsed = urlparse("https://www.example.com/index.html?query=arg#frag")
print(parsed.scheme)   # https
print(parsed.netloc)   # www.example.com

params = urlencode({"search": "python", "page": 1})
print(params)          # search=python&page=1

urllib.error

urllib.error defines the exceptions that can be raised by urllib.request:

Exception Description
URLError Base class for all urllib errors; raised when a URL cannot be opened (e.g., no network connection, bad host)
HTTPError Subclass of URLError; raised for HTTP error responses (e.g., 404, 500). Also acts as a file-like response object.
ContentTooShortError Raised by urlretrieve() when downloaded data is shorter than expected.

Example of error handling:

import urllib.request
import urllib.error

try:
    urllib.request.urlopen("https://www.example.com/missing")
except urllib.error.HTTPError as e:
    print(f"HTTP Error: {e.code}")
except urllib.error.URLError as e:
    print(f"URL Error: {e.reason}")

urllib.robotparser

urllib.robotparser provides the RobotFileParser class for reading and interpreting robots.txt files, which specify which parts of a website may be accessed by automated crawlers. It is commonly used in web scraping and crawler applications to respect the crawling policies of websites.

Example:

from urllib.robotparser import RobotFileParser

rp = RobotFileParser()
rp.set_url("https://www.example.com/robots.txt")
rp.read()
print(rp.can_fetch("*", "https://www.example.com/page"))

Relation to urllib3 and requests

Despite superficial naming similarity, urllib3 is an entirely independent third-party library unrelated to the Python standard library urllib. It was created in 2008 to address limitations of the built-in library, adding features such as:

The popular requests library is built on top of urllib3 and provides a higher-level, more user-friendly API for making HTTP requests. Both urllib3 and requests must be installed separately (e.g., via pip).

Library Part of stdlib Python version Notes
urllib Yes Python 1.2+ / 3.x Built-in; basic URL fetching and parsing
urllib2 Yes (Python 2 only) Python 1.6–2.7 Removed in Python 3; merged into urllib
urllib3 No Any Third-party; connection pooling, thread safety
requests No Any Third-party; built on urllib3; high-level API

Security considerations

HTTPS verification

By default, urllib.request.urlopen() verifies TLS/SSL certificates when making HTTPS requests. Disabling this via an unverified context is strongly discouraged in production environments as it leaves connections vulnerable to man-in-the-middle attacks.

SSRF

Because urllib can be used to open arbitrary URLs, applications that pass user-supplied input to urlopen() without validation may be vulnerable to Server-side request forgery (SSRF) attacks.

See also

Category:Python (programming language) libraries Category:Internet protocols Category:Free software programmed in Python Category:Application programming interfaces

Content Disclaimer

Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.

  1. The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
  2. There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
  3. It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
  4. Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
  5. Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.