ua-generator

repository·master·Indexed 41 days ago

https://github.com/iamdual/ua-generator

A Python library for generating random, realistic user-agent strings and corresponding Client Hint headers (Sec-CH-UA). It supports customization by device, platform, and browser, and includes a CLI tool (update_bot) for updating browser and OS version data.

Tokens
7K
Snippets
24
Records
26
Agent score
49%

What's inside ua-generator

  1. Generate a random user-agent

    master

    Use ua_generator.generate() to create a random user-agent object. By default, it returns a user-agent string representing a random combination of device, platform, and browser.

    import ua_generator
    
    ua = ua_generator.generate()
    print(ua) # Example: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/15.2 Safari/604.1.38
  2. Advanced customization using Options

    master

    For fine-grained control, use the ua_generator.options.Options class passed to the options parameter in generate().

    weighted_versions

    Set options.weighted_versions = True to increase the probability of selecting the latest versions.

    version_ranges

    Use options.version_ranges to restrict versions to specific ranges using VersionRange and Version objects.

    latest_versions

    • Set options.latest_versions = True to pick only the latest version.
    • Pass a dictionary to options.latest_versions to pick one of the latest N versions for specific browsers or platforms (e.g., {'chrome': 3}).

    tied_safari_version

    Set options.tied_safari_version = True to tie Safari versions to macOS/iOS versions.

    import ua_generator
    from ua_generator.options import Options
    from ua_generator.data.version import Version, VersionRange
    
    # Example: Version Ranges
    options = Options()
    options.version_ranges = {
        'chrome': VersionRange(125, 129),
        'edge': VersionRange(min_version=120),
        'macos': VersionRange(max_version=Version(10, 15, 7)),
    }
    ua = ua_generator.generate(browser='chrome', options=options)
    
    # Example: Latest N versions
    options = Options()
    options.latest_versions = {'chrome': 3, 'firefox': 1}
    ua = ua_generator.generate(options=options)
  3. Get HTTP headers including Client Hints

    master

    The ua.headers.get() method returns a dictionary of HTTP headers. By default, it includes user-agent, sec-ch-ua, sec-ch-ua-mobile, and sec-ch-ua-platform.

    You can extend these headers by calling ua.headers.accept_ch() with the names of the Client Hint headers you wish to include (e.g., Sec-CH-UA-Platform-Version).

    import ua_generator
    
    ua = ua_generator.generate(browser=['chrome', 'edge'])
    
    # Basic headers
    print(ua.headers.get())
    
    # Extended headers using Accept-CH
    ua.headers.accept_ch('Sec-CH-UA-Platform-Version, Sec-CH-UA-Full-Version-List')
    print(ua.headers.get())
  4. Access User-Agent properties and Client Hints (Sec-CH-UA)

    master

    The object returned by generate() contains several attributes for the raw text and structured Client Hint data:

    • ua.text: The full user-agent string.
    • ua.platform: The selected platform name.
    • ua.browser: The selected browser name.
    • ua.ch.brands: List of brand strings (e.g., "Not A(Brand";v="99", "Chromium";v="129").
    • ua.ch.brands_full_version_list: List of full version brand strings.
    • ua.ch.mobile: Mobile indicator ('?0' or '?1').
    • ua.ch.platform: The platform name for Client Hints.
    • ua.ch.platform_version: The platform version.
    • ua.ch.browser_version: The browser major version.
    • ua.ch.browser_full_version: The full browser version string.
    • ua.ch.bitness: Bit depth (e.g., '64').
    • ua.ch.architecture: CPU architecture (e.g., 'x86', 'arm').
    • ua.ch.wow64: WOW64 indicator ('?0' or '?1').
    import ua_generator
    
    ua = ua_generator.generate(device='desktop', browser=['chrome', 'edge'])
    print(ua.text)
    print(ua.ch.brands)
    print(ua.ch.platform_version)
  5. Customize user-agent generation with device, platform, and browser

    master

    You can restrict the generated user-agent by passing specific device, platform, or browser parameters to ua_generator.generate(). These parameters accept a single string or a list/tuple of strings.

    Supported values:

    • device: 'desktop', 'mobile'
    • platform: 'windows', 'macos', 'ios', 'linux', 'android'
    • browser: 'chrome', 'edge', 'firefox', 'safari'
    import ua_generator
    
    # Example: Desktop with either Chrome or Edge
    ua = ua_generator.generate(device='desktop', browser=['chrome', 'edge'])
    
    # Example: iOS or macOS with Edge
    ua = ua_generator.generate(platform=['ios', 'macos'], browser='edge')
  6. Integrate ua-generator with HTTP libraries

    master

    You can easily pass generated headers to common Python HTTP clients.

    Requests:

    import requests
    import ua_generator
    
    ua = ua_generator.generate(browser=['chrome', 'edge'])
    r = requests.get('https://httpbin.org/get', headers=ua.headers.get())

    HTTPX:

    import httpx
    import ua_generator
    
    ua = ua_generator.generate(browser=['chrome', 'edge'])
    r = httpx.get('https://httpbin.org/get', headers=ua.headers.get())

    urllib:

    import urllib.request
    import ua_generator
    
    ua = ua_generator.generate(browser=['chrome', 'edge'])
    request = urllib.request.Request('https://httpbin.org/get', headers=ua.headers.get())
    handler = urllib.request.urlopen(request)
    response = handler.read().decode('utf-8')

    Selenium: To use with Selenium, use execute_cdp_cmd to set extra headers and override the User Agent and Navigator metadata.

    import time
    from selenium import webdriver
    import ua_generator
    
    ua = ua_generator.generate(browser=['chrome', 'edge'], device=['desktop'])
    driver = webdriver.Chrome()
    driver.execute_cdp_cmd('Network.setExtraHTTPHeaders', {'headers': ua.headers.get()})
    driver.execute_cdp_cmd('Network.setUserAgentOverride', {
        'userAgent': ua.text,
        'userAgentMetadata': ua.navigator.get()
    })
    driver.get('https://browserleaks.com/client-hints')
  7. Access UserAgent properties and metadata

    master

    Once a UserAgent instance is initialized, it populates several attributes containing the generated data and metadata:

    • text: The actual User-Agent string (e.g., "Mozilla/5.0 ..."). Use str(ua) to get this value.
    • ch: A ClientHints object containing the generated Client Hints.
    • headers: A Headers object containing the HTTP headers associated with the User-Agent.
    • navigator: A Navigator object providing simulated navigator properties.
    • generator: The underlying Generator instance used to create the data.

    To get the raw string for use in requests, you can use the text attribute or simply cast the object to a string.

    ua = UserAgent(device='desktop')
    
    print(ua.text)          # The User-Agent string
    print(str(ua))          # Also returns the User-Agent string
    print(ua.headers)      # The associated HTTP headers
    print(ua.ch)            # The Client Hints
  8. Initialize a Version with random ranges

    master

    The Version class represents a software version consisting of major, minor, build, and patch components.

    When initializing a Version, you can pass an integer for a fixed value, or a tuple to specify a range. If a tuple is provided, the class will randomly select a value within that range using random.randrange(*x).

    Components can be set to None to indicate they are unspecified.

    from ua_generator.data.version import Version
    
    # Fixed version
    fixed = Version(major=125, minor=0, build=1, patch=0)
    
    # Version with random components within ranges
    # major will be between 120 and 130, minor between 0 and 5
    random_v = Version(major=(120, 130), minor=(0, 5))
  9. Use the ClientHints class to generate Client Hint headers

    master

    The ClientHints class is used to extract and format HTTP Client Hint data (Sec-CH-UA) based on a generated user-agent. It provides access to various browser and device attributes formatted specifically for HTTP headers.

    Attributes are accessed via property-like access (e.g., client_hints.platform), which internally uses __getattr__ to return serialized strings or lists compatible with the Client Hints specification.

    Available attributes include:

    • mobile: Boolean string (e.g., "?1" or "?0")
    • platform: The platform name (e.g., "Windows", "macOS", "iOS")
    • platform_version: The version of the operating system
    • brands: A list of brand/version objects
    • brands_full_version_list: A list of brand/version objects with full version numbers
    • browser_version: The major version of the browser
    • browser_full_version: The full version of the browser
    • bitness: The CPU bitness (e.g., "64")
    • architecture: The CPU architecture (e.g., "arm", "x86")
    • form_factors: A list of device form factors
    • model: The device model (primarily for Android)
    • wow64: Boolean indicating if the platform is Windows with WOW64 support
    from ua_generator import Generator
    from ua_generator.client_hints import ClientHints
    
    # Assuming 'gen' is an instance of generator.Generator
    gen = Generator()
    client_hints = ClientHints(gen)
    
    # Accessing formatted Client Hint values
    print(f"Platform: {client_hints.platform}")
    print(f"Mobile: {client_hints.mobile}")
    print(f"Brands: {client_hints.brands}")
  10. Configure user-agent generation with Options

    master

    The Options class allows you to customize how user-agents are generated. You can control version weighting, restrict versions to specific ranges, limit how many 'latest' versions are used for specific browsers or operating systems, and tie Safari versions to specific OS versions.

    Pass an instance of Options to the ua_generator.generate() function to apply your settings.

    from ua_generator import generate, Options
    from ua_generator.data.version import VersionRange
    
    options = Options(
        weighted_versions=True,
        tied_safari_version=True,
        latest_versions={
            'chrome': 3,
            'macos': 1,
        },
        version_ranges={
            'chrome': VersionRange(125, 129),
            'edge': VersionRange(min_version=120),
        },
    )
    
    ua = generate(options=options)
  11. Filter versions using VersionRange

    master

    The VersionRange class allows you to define a boundary for version filtering. You can initialize it with min_version and max_version as Version objects or as integers (which are treated as the major component).

    Use the filter(versions: List[Version]) method to return a list of versions that fall within the specified range.

    Behavioral Notes:

    • If a component in the boundary is None, it acts as a wildcard.
    • For max_version, omitted components are treated as very large numbers (allowing VersionRange(125, 129) to match any 129.x release).
    • For min_version, omitted components are treated as 0.
    from ua_generator.data.version import Version, VersionRange
    
    # Define a range from version 120 to 125
    vr = VersionRange(min_version=120, max_version=125)
    
    # List of versions to test
    versions = [
        Version(119, 0), 
        Version(120, 5), 
        Version(125, 0), 
        Version(126, 0)
    ]
    
    filtered = vr.filter(versions)
    # Result: [Version(120, 5), Version(125, 0)]