Adapted py3k urllib fixes from @ukaslu (4d40218) to be py2 compatible as well