Coder Social home page Coder Social logo

nexb / python-publicsuffix2 Goto Github PK

View Code? Open in Web Editor NEW
29.0 11.0 15.0 647 KB

A small Python library to deal with publicsuffix data (includes a bundled PSL as "package data") in a wheel friendly format. Fork and continuation of Tomaž Šolc's "publicsuffix"

Python 100.00%
publicsuffix python tld top-level-domain

python-publicsuffix2's Introduction

Public Suffix List module for Python

This module allows you to get the public suffix, as well as the registrable domain, of a domain name using the Public Suffix List from http://publicsuffix.org

A public suffix is a domain suffix under which you can register domain names, or under which the suffix owner does not control the subdomains. Some examples of public suffixes in the former example are ".com", ".co.uk" and "pvt.k12.wy.us"; examples of the latter case are "github.io" and "blogspot.com". The public suffix is sometimes referred to as the effective or extended TLD (eTLD). Accurately knowing the public suffix of a domain is useful when handling web browser cookies, highlighting the most important part of a domain name in a user interface or sorting URLs by web site. It is also used in a wide range of research and applications that leverages Domain Name System (DNS) data.

This module builds the public suffix list as a Trie structure, making it more efficient than other string-based modules available for the same purpose. It can be used effectively in large-scale distributed environments, such as PySpark.

This Python module includes with a copy of the Public Suffix List (PSL) so that it is usable out of the box. Newer versions try to provide reasonably fresh copies of this list. It also includes a convenience method to fetch the latest list. The PSL does change regularly.

The code is a fork of the publicsuffix package and includes the same base API. In addition, it contains a few variants useful for certain use cases, such as the option to ignore wildcards or return only the extended TLD (eTLD). You just need to import publicsuffix2 instead.

The public suffix list is now provided in UTF-8 format. To correctly process IDNA-encoded domains, either the query or the list must be converted. By default, the module converts the PSL. If your use case includes UTF-8 domains, e.g., '食狮.com.cn', you'll need to set the IDNA-encoding flag to False on instantiation (see examples below). Failure to use the correct encoding for your use case can lead to incorrect results for domains that utilize unicode characters.

The code is MIT-licensed and the publicsuffix data list is MPL-2.0-licensed.

master branch tests status develop branch tests status

Usage

Install with:

pip install publicsuffix2

The module provides functions to obtain the base domain, or sld, of an fqdn, as well as one to get just the public suffix. In addition, the functions a number of boolean parameters that control how wildcards are handled. In addition to the functions, the module exposes a class that parses the PSL, and allows for more control.

The module provides two equivalent functions to query a domain name, and return the base domain, or second-level-doamin; get_public_suffix() and get_sld():

>>> from publicsuffix2 import get_public_suffix
>>> get_public_suffix('www.example.com')
'example.com'
>>> get_sld('www.example.com')
'example.com'
>>> get_public_suffix('www.example.co.uk')
'example.co.uk'
>>> get_public_suffix('www.super.example.co.uk')
'example.co.uk'
>>> get_sld("co.uk")  # returns eTLD as is
'co.uk'

This function loads and caches the public suffix list. To obtain the latest version of the PSL, use the fetch() function to first download the latest version. Alternatively, you can pass a custom list.

For more control, there is also a class that parses a Public Suffix List and allows the same queries on individual domain names:

>>> from publicsuffix2 import PublicSuffixList
>>> psl = PublicSuffixList()
>>> psl.get_public_suffix('www.example.com')
'example.com'
>>> psl.get_public_suffix('www.example.co.uk')
'example.co.uk'
>>> psl.get_public_suffix('www.super.example.co.uk')
'example.co.uk'
>>> psl.get_sld('www.super.example.co.uk')
'example.co.uk'

Note that the host part of an URL can contain strings that are not plain DNS domain names (IP addresses, Punycode-encoded names, name in combination with a port number or a username, etc.). It is up to the caller to ensure only domain names are passed to the get_public_suffix() method.

The get_public_suffix() function and the PublicSuffixList class initializer accept an optional argument pointing to a public suffix file. This can either be a file path, an iterable of public suffix lines, or a file-like object pointing to an opened list:

>>> from publicsuffix2 import get_public_suffix
>>> psl_file = 'path to some psl data file'
>>> get_public_suffix('www.example.com', psl_file)
'example.com'

Note that when using get_public_suffix() a global cache keeps the latest provided suffix list data. This will use the cached latest loaded above:

>>> get_public_suffix('www.example.co.uk')
'example.co.uk'

IDNA-encoding. The public suffix list is now in UTF-8 format. For those use cases that include IDNA-encoded domains, the list must be converted. Publicsuffix2 includes idna encoding as a parameter of the PublicSuffixList initialization and is true by default. For UTF-8 use cases, set the idna parameter to False:

>>> from publicsuffix2 import PublicSuffixList
>>> psl = PublicSuffixList(idna=True)  # on by default
>>> psl.get_public_suffix('www.google.com')
'google.com'
>>> psl = PublicSuffixList(idna=False)  # use UTF-8 encodings
>>> psl.get_public_suffix('食狮.com.cn')
'食狮.com.cn'

Ignore wildcards. In some use cases, particularly those related to large-scale domain processing, the user might want to ignore wildcards to create more aggregation. This is possible by setting the parameter wildcard=False.:

>>> psl.get_public_suffix('telinet.com.pg', wildcard=False)
'com.pg'
>>> psl.get_public_suffix('telinet.com.pg', wildcard=True)
'telinet.com.pg'

Require valid eTLDs (strict). In the publicsuffix2 module, a domain with an invalid TLD will still return return a base domain, e.g,:

>>> psl.get_public_suffix('www.mine.local')
'mine.local'

This is useful for many use cases, while in others, we want to ensure that the domain includes a valid eTLD. In this case, the boolean parameter strict provides a solution. If this flag is set, an invalid TLD will return None.:

>>> psl.get_public_suffix('www.mine.local', strict=True) is None
True

Return eTLD only. The standard use case for publicsuffix2 is to return the registrable, or base, domain according to the public suffix list. In some cases, however, we only wish to find the eTLD itself. This is available via the get_tld() method.:

>>> psl.get_tld('www.google.com')
'com'
>>> psl.get_tld('www.google.co.uk')
'co.uk'

All of the methods and functions include the wildcard and strict parameters.

For convenience, the public method get_sld() is available. This is identical to the method get_public_suffix() and is intended to clarify the output for some users.

To update the bundled suffix list use the provided setup.py command:

python setup.py update_psl

The update list will be saved in src/publicsuffix2/public_suffix_list.dat and you can build a new wheel with this bundled data.

Alternatively, there is a fetch() function that will fetch the latest version of a Public Suffix data file from https://publicsuffix.org/list/public_suffix_list.dat You can use it this way:

>>> from publicsuffix2 import get_public_suffix
>>> from publicsuffix2 import fetch
>>> psl_file = fetch()
>>> get_public_suffix('www.example.com', psl_file)
'example.com'

Note that the once loaded, the data file is cached and therefore fetched only once.

The extracted public suffix list, that is the tlds and their modifiers, is put into an instance variable, tlds, which can be accessed as an attribute, tlds.:

>>> psl = PublicSuffixList()
>>> psl.tlds[:5]
['ac',
'com.ac',
'edu.ac',
'gov.ac',
'net.ac']

Using the module in large-scale processing If using this library in large-scale pyspark processing, you should instantiate the class as a global variable, not within a user function. The class methods can then be used within user functions for distributed processing.

Source

Get a local copy of the development repository. The development takes place in the develop branch. Stable releases are tagged in the master branch:

git clone https://github.com/nexB/python-publicsuffix2.git

History

This code is forked from Tomaž Šolc's fork of David Wilson's code.

Tomaž Šolc's code originally at:

https://www.tablix.org/~avian/git/publicsuffix.git

Copyright (c) 2014 Tomaž Šolc <[email protected]>

David Wilson's code was originally at:

http://code.google.com/p/python-public-suffix-list/

Copyright (c) 2009 David Wilson

License

The code is MIT-licensed. The vendored public suffix list data from Mozilla is under the MPL-2.0.

Copyright (c) 2015 nexB Inc. and others.

Copyright (c) 2014 Tomaž Šolc <[email protected]>

Copyright (c) 2009 David Wilson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

python-publicsuffix2's People

Contributors

avian2 avatar hiratara avatar kevin-olbrich avatar kitterma avatar knitcode avatar pombredanne avatar vpiserchia avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-publicsuffix2's Issues

Various issues with 2.2018 versions

There have been two recent updates to this package on pypi which are quite strange in various ways:

  • The package can no longer be imported as publicsuffix like the docs show, it must now be publicsuffix2 (so the example code in the docs no longer works)
  • The changelog on pypi hasn't been updated for the most recent 2 releases, and this repo also hasn't been updated in years
  • The newest version (2.20180921.2) no longer seems to download the publicsuffix file, it just uses the one included?

Are you still the maintainer of this package? What's happening with it?

Dashes cause parsing error

Try these examples, this looks like a bug to me. Note that all I did was remove the dash from "compute-1". I would expect the tld to be "compute-1.amazonaws.com" and the sld to be "amazonaws.com".

>>> get_tld('ec2-107-21-74-29.compute-1.amazonaws.com')
'ec2-107-21-74-29.compute-1.amazonaws.com'
>>> get_sld('ec2-107-21-74-29.compute-1.amazonaws.com')
'ec2-107-21-74-29.compute-1.amazonaws.com'
>>> get_sld('ec2-107-21-74-29.compute1.amazonaws.com')
'compute1.amazonaws.com'
>>> get_tld('ec2-107-21-74-29.compute1.amazonaws.com')
'amazonaws.com'

Wildcard eTLDs not correctly handled

There are currently 74 wildcard eTLDs in the PSL - for example, the .bd gTLD is solely represented by:

// bd : https://en.wikipedia.org/wiki/.bd
*.bd

One example domain would be www.zymak.com.bd. Calling get_public_suffix("www.zymak.com.bd") incorrectly returns "com.bd" instead of "zymak.com.bd"

Including upstream list as submodule/subtree would be more transparent

During packaging of python-publicsuffix2 I realized, that downloading the publicsuffix list during build time makes it unreproducible (any time the package is rebuilt, it will have a different list).

My suggestion would be to include the publicsuffix list from upstream directly as e.g. a git submodule or git subtree (the latter is preferred as this way the files actually end up in an automatically generated tarball on github when tagging a release) and not download it during build time at all to ensure reproducibility raise transparency.
The data lives in this repository already, so it could also be copied manually, but IMHO a subtree or submodule is the more transparent way of dealing with this.

Currently only the wheel on pypi.org is really ensured to carry the currently bundled version of the publicsuffix list. For anyone else building this package, this assumption is not valid.

Strict=True Returns "amazonaws.com" as an eTLD

The following code:

from publicsuffix2 import PublicSuffixList

psl = PublicSuffixList(idna=True)
print(psl.get_public_suffix('snack.amazonaws.com',strict=True))

returns snack.amazonaws.com when it should return amazonaws.com.

Mislabeling of eTLD-`n`

As mentioned in publicsuffix/list#1872 (comment)

Multiple psl libraries share the same bug while handling wildcards.

I went over all the FOSS implementations in https://publicsuffix.org/learn/ , and I found 3 of them behave funny for wildcard domains. In particular:

Seems to all mislabel eTLD-n x [eTLD minus n] (with n from 0 to infinite), as an eTLD, if another eTLD y is defined as a subdomain of that x eTLD-n.

As an example publicsuffix2 behaviour with the following patch:

 // Linode : https://linode.com
 // Submitted by <[email protected]>
 members.linode.com
-nodebalancer.linode.com
+*.nodebalancer.linode.com
+*.linodeobjects.com
+ip.linodeusercontent.com

Example here:

291734330-d38c352b-b420-45fb-93dc-438ebbea2f02

This bug has already been reported in this library here

tests missing in sdist/ incoherent tagging vs tarball naming

Hi! I'm packaging python-publisuffx2 for Arch Linux and would like to be able to run tests from the sdist tarball on pypi.
Although the test files should be included (according to MANIFEST.in), they are not.

As a test I've checked out the current latest version (release-2.2019-12-21) and ran python setup.py sdist myself. The files are included in the created sdist tarball, which makes me wonder how the sdists for pypi.org were created.

It would be great, if the sdists included the tests, as currently I have to use the github tarballs to be able to run the tests.

This leads me to the second topic: The tag naming and resulting tarballs are incoherent and lead to more complicated string substitutions to track upstream and/or use the github source tarball vs. using pypi's sdist tarball: release-2.2019-12-21 -> publicsuffix2-2.20191221.tar.gz
I understand, that the tagging scheme so far follows an ISO standard for the date, but it would be more coherent to strip the hyphens to be in line with the resulting tarball/wheel: e.g. release-2.20191221 -> publicsuffix2-2.20191221.tar.gz

Are these behaviors correct?

I install this library and notice that it behaves differently from the spec.

For example, spec says,

checkPublicSuffix('ac.jp', null);

But your tests says:

assert 'ac.jp' == psl.get_sld('ac.jp')

get_tld() returns more weird results.

>>> psl.get_tld("ac.jp")
'jp'

PSL has ac.jp entry, but publicsuffix2 returns 'jp' . I tried other python libraries, but they all returns ac.jp .

>>> from publicsuffixlist import PublicSuffixList
>>> psl = PublicSuffixList()
>>> psl.publicsuffix("ac.jp")
'ac.jp'
>>> from dnspy.dnspy import Dnspy
>>> d = Dnspy()
>>> d.etld("ac.jp")
'ac.jp'
>>> import psl
>>> psl.domain_suffixes("ac.jp").public
'ac.jp'

pages.example.com suffix declaration causes get_tld('example.com') == 'example.com'

publicsuffix2 mishandles the case where, given the declaration of some public suffix, all suffixes of that suffix are seen as their own TLDs. E.g., given the declaration of git-pages.rit.edu as a public suffix, get_tld('rit.edu') returns 'rit.edu', whereas it really should return 'edu':

Python 3.7.7 (default, Mar 14 2020, 02:39:38)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from publicsuffix2 import PublicSuffixList
>>> psl = PublicSuffixList()
>>> psl.get_tld("foo.git-pages.rit.edu")
'git-pages.rit.edu'  # CORRECT
>>> psl.get_tld("git-pages.rit.edu")
'git-pages.rit.edu'  # WRONG, should be 'edu'
>>> psl.get_tld("rit.edu")
'rit.edu'            # WRONG, should be 'edu'
>>> psl.get_tld("edu")
'edu'                # CORRECT, but probably out of accident

code upgrade

hi, i submitted a PR in March to fix issues related to the now-UTF8 encoding of the PSL and add some functionality. There were some bugs in that which eluded my test checks. Those are now fixed. I am unable to request a review in the PR. My preference is to have the changes merged into publicsuffix2, so we don't have to change our various code bases to a new module name. appreciate a review and either accept, or reject and we'll set up a new module in pypi. thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.