mirror of
https://github.com/RustyRaptor/mal-scraper.git
synced 2026-12-03 15:35:18 -07:00
Improve anime processing
This commit is contained in:
1 parent
bd7fee100e
commit
e1cc68a9c7
23 files changed
+7642
-124
No files matched your search
+7
-1
@@ -1,7 +1,13 @@
|
||||
|
||||
=========
|
||||
Changelog
|
||||
=========
|
||||
|
||||
Development
|
||||
-----------------------------------------
|
||||
|
||||
* Fix various issues on anime pages
|
||||
* Rename `retrieve_anime` to `get_anime` for consistency (backwards-incompatible)
|
||||
|
||||
0.2.1 (2017-05-01)
|
||||
-----------------------------------------
|
||||
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
============
|
||||
Contributing
|
||||
============
|
||||
========================
|
||||
Contributing/Development
|
||||
========================
|
||||
|
||||
Contributions are welcome, and they are greatly appreciated! Every
|
||||
little bit helps, and credit will always be given.
|
||||
|
||||
+7
-4
@@ -51,14 +51,17 @@ Overview
|
||||
MyAnimeList web scraper is a Python library for gathering data for analysis.
|
||||
|
||||
|
||||
Usage
|
||||
=====
|
||||
Installation & Usage
|
||||
====================
|
||||
|
||||
Use the `online documentation <https://mal-scraper.readthedocs.io/>`_, and just::
|
||||
Installation is simple::
|
||||
|
||||
pip install mal-scraper
|
||||
|
||||
We follow `Semantic Versioning <http://semver.org/>`_.
|
||||
Please use the `documentation <https://mal-scraper.readthedocs.io/>`_ for
|
||||
the reference and usage examples.
|
||||
|
||||
For your convenience follow `Semantic Versioning <http://semver.org/>`_.
|
||||
|
||||
|
||||
Development
|
||||
|
||||
@@ -6,7 +6,6 @@ Contents
|
||||
:maxdepth: 2
|
||||
|
||||
readme
|
||||
installation
|
||||
usage
|
||||
reference/index
|
||||
contributing
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
============
|
||||
Installation
|
||||
============
|
||||
|
||||
At the command line::
|
||||
|
||||
pip install mal-scraper
|
||||
@@ -1,11 +1,12 @@
|
||||
Reference
|
||||
=========
|
||||
|
||||
The public API is available directly by importing from `mal_scraper`::
|
||||
The public API is available directly by importing from `mal_scraper`,
|
||||
for example::
|
||||
|
||||
import mal_scraper
|
||||
|
||||
mal_scraper.retrieve_anime # Core API
|
||||
mal_scraper.get_anime # Core API
|
||||
mal_scraper.AiringStatus.ongoing # Constants/Enumerations
|
||||
mal_scraper.ParseError # Exceptions
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Core API
|
||||
========
|
||||
|
||||
It currently supports retrieving Anime, User Profile/Stats, and User-Anime Info.
|
||||
The library supports retrieving Anime, User Profile/Stats, and User-Anime Info.
|
||||
|
||||
Anime and Users are identified by `id_ref`s which are integers for anime and
|
||||
strings for Users, so while you can enumerate through Anime, you must 'discover'
|
||||
@@ -15,4 +15,4 @@ Users.
|
||||
:members:
|
||||
:imported-members:
|
||||
:exclude-members: AgeRating, AiringStatus, ConsumptionStatus, Format,
|
||||
ParseError
|
||||
Season, ParseError
|
||||
+30
-5
@@ -1,7 +1,32 @@
|
||||
=====
|
||||
Usage
|
||||
=====
|
||||
==============
|
||||
Usage/Examples
|
||||
==============
|
||||
|
||||
To use MyAnimeList Scraper in a project::
|
||||
To use MyAnimeList Scraper in a project, for example to retrieve
|
||||
anime metadata::
|
||||
|
||||
import mal_scraper
|
||||
import mal_scraper
|
||||
import mycode
|
||||
|
||||
next_id_ref = mycode.last_id_ref() + 1
|
||||
|
||||
try:
|
||||
meta, data = mal_scraper.get_anime(next_id_ref)
|
||||
except requests.exceptions.HTTPError as err:
|
||||
code = err.response.status_code
|
||||
if code == 404:
|
||||
print('Anime #%d does not exist (404)', next_id_ref)
|
||||
mycode.ignore_id_ref(next_id_ref)
|
||||
else:
|
||||
# Retry on network/server/request errors
|
||||
print('Anime #%d HTTP error (%d)', next_id_ref, code)
|
||||
mycode.mark_for_retry(next_id_ref)
|
||||
else:
|
||||
print('Adding Anime #%d', meta['id_ref'])
|
||||
mycode.add_anime(
|
||||
id_ref=meta['id_ref'],
|
||||
anime_information_dated_at=meta['when'],
|
||||
name=data['name'],
|
||||
episodes=data['episodes'],
|
||||
# Ignore other data
|
||||
)
|
||||
@@ -28,6 +28,7 @@ addopts =
|
||||
|
||||
[isort]
|
||||
line_length=100
|
||||
multi_line_output=5
|
||||
known_first_party=mal_scraper
|
||||
default_section=THIRDPARTY
|
||||
forced_separate=test_mal_scraper
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
__version__ = "0.2.1"
|
||||
|
||||
# Import Public API
|
||||
from .anime import retrieve_anime # noqa
|
||||
from .anime import get_anime # noqa
|
||||
from .consts import AgeRating, AiringStatus, ConsumptionStatus, Format, Season # noqa
|
||||
from .exceptions import ParseError # noqa
|
||||
from .users import discover_users, get_user_anime_list, get_user_stats # noqa
|
||||
from .users import ( # noqa
|
||||
discover_users, discover_users_from_html, get_user_anime_list, get_user_stats
|
||||
)
|
||||
|
||||
# Don't use this
|
||||
FORCE_HTTP = False
|
||||
+82
-60
@@ -1,3 +1,4 @@
|
||||
import itertools
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
@@ -8,7 +9,6 @@ from .exceptions import MissingTagError, ParseError
|
||||
from .mal_utils import get_date
|
||||
from .requester import request_passthrough
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Future interface?
|
||||
@@ -17,8 +17,8 @@ logger = logging.getLogger(__name__)
|
||||
# pass
|
||||
|
||||
|
||||
def retrieve_anime(id_ref=1, requester=request_passthrough):
|
||||
"""mal_scraper.retrieve_anime(id_ref=1, requester)
|
||||
def get_anime(id_ref=1, requester=request_passthrough):
|
||||
"""mal_scraper.get_anime(id_ref=1, requester)
|
||||
|
||||
Return the information for a particular show.
|
||||
|
||||
@@ -35,16 +35,17 @@ def retrieve_anime(id_ref=1, requester=request_passthrough):
|
||||
|
||||
`data`::
|
||||
|
||||
{
|
||||
'name': str,
|
||||
'name_english': str,
|
||||
'format': mal_scraper.Format,
|
||||
'episodes': int, or None when MAL does not know,
|
||||
'airing_status': mal_scraper.AiringStatus,
|
||||
'airing_started': datetime,
|
||||
'airing_finished': datetime, or None when MAL does not know,
|
||||
'airing_premiere': tuple(Year (int), Season (mal_scraper.Season)),
|
||||
}
|
||||
{
|
||||
'name': str,
|
||||
'name_english': str,
|
||||
'format': mal_scraper.Format,
|
||||
'episodes': int, or None when MAL does not know,
|
||||
'airing_status': mal_scraper.AiringStatus,
|
||||
'airing_started': date,
|
||||
'airing_finished': date, or None when MAL does not know,
|
||||
'airing_premiere': tuple(Year (int), Season (mal_scraper.Season))
|
||||
or None (for films, OVAs, specials, ONAs and music),
|
||||
}
|
||||
|
||||
See also :class:`.Format`, :class:`.AiringStatus`, :class:`.Season`.
|
||||
|
||||
@@ -60,17 +61,15 @@ def retrieve_anime(id_ref=1, requester=request_passthrough):
|
||||
next_anime = 1
|
||||
|
||||
try:
|
||||
meta, data = mal_scraper.retrieve_anime(next_anime)
|
||||
meta, data = mal_scraper.get_anime(next_anime)
|
||||
except mal_scraper.ParseError as err:
|
||||
logger.error('Investigate page %s with error %d', err.url, err.code)
|
||||
except Network and Request Errors:
|
||||
pass # TODO docs, retry etc.
|
||||
except NetworkandRequestErrors: # Pseudo-code (TODO: These docs)
|
||||
pass # Retry?
|
||||
else:
|
||||
mycode.save_data(data, when=meta['when'])
|
||||
|
||||
next_anime = meta['id_ref'] + 1
|
||||
|
||||
.. py:sig:: mal_scrape.retrieve_anime(id_ref=1, requester)
|
||||
"""
|
||||
url = get_url_from_id_ref(id_ref)
|
||||
|
||||
@@ -78,21 +77,25 @@ def retrieve_anime(id_ref=1, requester=request_passthrough):
|
||||
response.raise_for_status() # May raise
|
||||
|
||||
soup = BeautifulSoup(response.content, 'html.parser')
|
||||
data = retrieve_anime_from_soup(soup) # May raise
|
||||
data = get_anime_from_soup(soup) # May raise
|
||||
|
||||
meta = {
|
||||
'when': datetime.utcnow(),
|
||||
'id_ref': id_ref,
|
||||
'response': response,
|
||||
}
|
||||
|
||||
return Retrieved(meta, data)
|
||||
|
||||
|
||||
def get_url_from_id_ref(id_ref):
|
||||
return 'http://myanimelist.net/anime/{:d}'.format(id_ref)
|
||||
# Use HTTPS to avoid auto-redirect from HTTP (except for tests)
|
||||
from .__init__ import FORCE_HTTP
|
||||
protocol = 'http' if FORCE_HTTP else 'https'
|
||||
return '{}://myanimelist.net/anime/{:d}'.format(protocol, id_ref)
|
||||
|
||||
|
||||
def retrieve_anime_from_soup(soup):
|
||||
def get_anime_from_soup(soup):
|
||||
"""Return the anime information from a soup of HTML.
|
||||
|
||||
Args:
|
||||
@@ -105,32 +108,33 @@ def retrieve_anime_from_soup(soup):
|
||||
'name': str,
|
||||
'name_english': str,
|
||||
'format': mal_scraper.Format,
|
||||
'episodes': int,
|
||||
'airing_status': TODO,
|
||||
'airing_started': TODO,
|
||||
'airing_finished': TODO,
|
||||
'airing_premiere': TODO,
|
||||
'episodes': int, or None when MAL does not know,
|
||||
'airing_status': mal_scraper.AiringStatus,
|
||||
'airing_started': date,
|
||||
'airing_finished': date, or None when MAL does not know,
|
||||
'airing_premiere': tuple(Year (int), Season (mal_scraper.Season))
|
||||
or None (for films, OVAs, specials, ONAs and music),
|
||||
}
|
||||
|
||||
Raises:
|
||||
ParseError: If any component of the page could not be processed
|
||||
or was unexpected.
|
||||
"""
|
||||
process = {
|
||||
'name': _get_name,
|
||||
'name_english': _get_english_name,
|
||||
'format': _get_format,
|
||||
'episodes': _get_episodes,
|
||||
'airing_status': _get_airing_status,
|
||||
'airing_started': _get_start_date,
|
||||
'airing_finished': _get_end_date,
|
||||
'airing_premiere': _get_airing_premiere,
|
||||
}
|
||||
process = [
|
||||
('name', _get_name),
|
||||
('name_english', _get_english_name),
|
||||
('format', _get_format),
|
||||
('episodes', _get_episodes),
|
||||
('airing_status', _get_airing_status),
|
||||
('airing_started', _get_start_date),
|
||||
('airing_finished', _get_end_date),
|
||||
('airing_premiere', _get_airing_premiere),
|
||||
]
|
||||
|
||||
data = {}
|
||||
for tag, func in process.items():
|
||||
for tag, func in process:
|
||||
try:
|
||||
result = func(soup)
|
||||
result = func(soup, data)
|
||||
except ParseError as err:
|
||||
logger.debug('Failed to process tag %s', tag)
|
||||
err.specify_tag(tag)
|
||||
@@ -141,7 +145,7 @@ def retrieve_anime_from_soup(soup):
|
||||
return data
|
||||
|
||||
|
||||
def _get_name(soup):
|
||||
def _get_name(soup, data=None):
|
||||
tag = soup.find('span', itemprop='name')
|
||||
if not tag:
|
||||
raise MissingTagError('name')
|
||||
@@ -150,33 +154,38 @@ def _get_name(soup):
|
||||
return text
|
||||
|
||||
|
||||
def _get_english_name(soup):
|
||||
def _get_english_name(soup, data=None):
|
||||
pretag = soup.find('span', string='English:')
|
||||
|
||||
# This is not always present (https://myanimelist.net/anime/15)
|
||||
if not pretag:
|
||||
raise MissingTagError('english name')
|
||||
return ''
|
||||
|
||||
text = pretag.next_sibling.strip()
|
||||
return text
|
||||
|
||||
|
||||
def _get_format(soup):
|
||||
def _get_format(soup, data=None):
|
||||
pretag = soup.find('span', string='Type:')
|
||||
if not pretag:
|
||||
raise MissingTagError('type')
|
||||
|
||||
text = pretag.find_next('a').string.strip().upper()
|
||||
format_ = {
|
||||
'TV': Format.tv
|
||||
}.get(text, None)
|
||||
for text in itertools.islice(pretag.next_siblings, 3):
|
||||
text = text.string.strip()
|
||||
if text:
|
||||
break
|
||||
else:
|
||||
text = None
|
||||
|
||||
format_ = Format.mal_to_enum(text)
|
||||
if not format_: # pragma: no cover
|
||||
# Either we missed a format, or MAL changed the webpage
|
||||
raise ParseError('type', 'Unknown format for the text "{}"'.format(text))
|
||||
raise ParseError('Unable to identify format from "{}"'.format(text))
|
||||
|
||||
return format_
|
||||
|
||||
|
||||
def _get_episodes(soup):
|
||||
def _get_episodes(soup, data=None):
|
||||
pretag = soup.find('span', string='Episodes:')
|
||||
if not pretag:
|
||||
raise MissingTagError('episodes')
|
||||
@@ -189,12 +198,12 @@ def _get_episodes(soup):
|
||||
episodes_number = int(episodes_text)
|
||||
except (ValueError, TypeError): # pragma: no cover
|
||||
# MAL probably changed the webpage
|
||||
raise ParseError('episodes', 'Unable to convert text "%s" to int' % episodes_text)
|
||||
raise ParseError('Unable to convert text "%s" to int' % episodes_text)
|
||||
|
||||
return episodes_number
|
||||
|
||||
|
||||
def _get_airing_status(soup):
|
||||
def _get_airing_status(soup, data=None):
|
||||
pretag = soup.find('span', string='Status:')
|
||||
if not pretag:
|
||||
raise MissingTagError('status')
|
||||
@@ -207,12 +216,12 @@ def _get_airing_status(soup):
|
||||
|
||||
if not status: # pragma: no cover
|
||||
# MAL probably changed the website
|
||||
raise ParseError('status', 'Unable to identify text "%s"' % status_text)
|
||||
raise ParseError('Unable to identify status from "%s"' % status_text)
|
||||
|
||||
return status
|
||||
|
||||
|
||||
def _get_start_date(soup):
|
||||
def _get_start_date(soup, data=None):
|
||||
pretag = soup.find('span', string='Aired:')
|
||||
if not pretag:
|
||||
raise MissingTagError('aired')
|
||||
@@ -224,18 +233,24 @@ def _get_start_date(soup):
|
||||
start_date = get_date(start_text)
|
||||
except ValueError: # pragma: no cover
|
||||
# MAL probably changed their website
|
||||
raise ParseError('airing start date', 'Cannot process text "%s"' % start_text)
|
||||
raise ParseError('Unable to identify date from "%s"' % start_text)
|
||||
|
||||
return start_date
|
||||
|
||||
|
||||
def _get_end_date(soup):
|
||||
def _get_end_date(soup, data=None):
|
||||
pretag = soup.find('span', string='Aired:')
|
||||
if not pretag:
|
||||
raise MissingTagError('aired')
|
||||
|
||||
aired_text = pretag.next_sibling.strip()
|
||||
end_text = aired_text.split(' to ')[1]
|
||||
date_range_text = aired_text.split(' to ')
|
||||
|
||||
# Not all Aired tags have a date range (https://myanimelist.net/anime/5)
|
||||
try:
|
||||
end_text = date_range_text[1]
|
||||
except IndexError:
|
||||
return None
|
||||
|
||||
if end_text == '?':
|
||||
return None
|
||||
@@ -244,27 +259,34 @@ def _get_end_date(soup):
|
||||
end_date = get_date(end_text)
|
||||
except ValueError: # pragma: no cover
|
||||
# MAL probably changed their website
|
||||
raise ParseError('airing end date', 'Cannot process text "%s"' % end_text)
|
||||
raise ParseError('Unable to identify date from "%s"' % end_text)
|
||||
|
||||
return end_date
|
||||
|
||||
|
||||
def _get_airing_premiere(soup):
|
||||
def _get_airing_premiere(soup, data):
|
||||
pretag = soup.find('span', string='Premiered:')
|
||||
if not pretag:
|
||||
raise MissingTagError('premiered')
|
||||
# Film: https://myanimelist.net/anime/5
|
||||
# OVA: https://myanimelist.net/anime/44
|
||||
# ONA: https://myanimelist.net/anime/574
|
||||
# TODO: Missing Special, Music links
|
||||
if data['format'] in (Format.film, Format.ova, Format.special, Format.ona, Format.music):
|
||||
return None
|
||||
else:
|
||||
raise MissingTagError('premiered')
|
||||
|
||||
season, year = pretag.find_next('a').string.lower().split(' ')
|
||||
|
||||
season = Season.mal_to_enum(season)
|
||||
if season is None:
|
||||
# MAL probably changed their website
|
||||
raise ParseError('premiered', 'Unable to identify season "%s"' % season)
|
||||
raise ParseError('Unable to identify season from "%s"' % season)
|
||||
|
||||
try:
|
||||
year = int(year)
|
||||
except (ValueError, TypeError): # pragma: no cover
|
||||
# MAL probably changed their website
|
||||
raise ParseError('premiered', 'Unable to identify year "%s"' % year)
|
||||
raise ParseError('Unable to identify year from "%s"' % year)
|
||||
|
||||
return (year, season)
|
||||
@@ -1,9 +1,8 @@
|
||||
"""All constants/enumerations available directly from `mal_scraper.x`"""
|
||||
"""All constants/enumerations are available directly from `mal_scraper.x`"""
|
||||
|
||||
from collections import namedtuple
|
||||
from enum import Enum, unique
|
||||
|
||||
|
||||
Retrieved = namedtuple('Retrieved', ['meta', 'data'])
|
||||
"""When successfully retrieving from a web-page
|
||||
|
||||
@@ -50,7 +49,7 @@ class Season(Enum):
|
||||
|
||||
@classmethod
|
||||
def mal_to_enum(cls, text):
|
||||
"""Return the enum from the MAL string, or None"""
|
||||
"""Return the enum from the MAL string, or None."""
|
||||
return {
|
||||
'winter': cls.winter,
|
||||
'spring': cls.spring,
|
||||
@@ -59,10 +58,26 @@ class Season(Enum):
|
||||
}.get(text.lower().strip())
|
||||
|
||||
|
||||
@unique
|
||||
class Format(Enum):
|
||||
"""The media format of a media item."""
|
||||
tv = 'TV'
|
||||
film = movie = 'FILM' # https://myanimelist.net/anime/5
|
||||
ova = 'OVA' # https://myanimelist.net/anime/44
|
||||
special = 'SPECIAL'
|
||||
ona = 'ONA' # (Original Net Animation) https://myanimelist.net/anime/574
|
||||
music = 'MUSIC' # Seriously? https://myanimelist.net/anime/731
|
||||
|
||||
@classmethod
|
||||
def mal_to_enum(cls, text):
|
||||
"""Return the enum from the MAL string, or None."""
|
||||
return {
|
||||
'tv': cls.tv,
|
||||
'movie': cls.film,
|
||||
'ova': cls.ova,
|
||||
'special': cls.special,
|
||||
'ona': cls.ona,
|
||||
'music': cls.music,
|
||||
}.get(text.lower().strip())
|
||||
|
||||
|
||||
@unique
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
"""All exceptions are available directly from `mal_scraper.x`"""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MalScraperError(Exception):
|
||||
"""All exceptions raised by this library."""
|
||||
"""Parent to all exceptions raised by this library."""
|
||||
|
||||
|
||||
class ParseError(MalScraperError):
|
||||
@@ -36,10 +38,10 @@ class ParseError(MalScraperError):
|
||||
|
||||
|
||||
class MissingTagError(ParseError):
|
||||
"""The tag is missing from the soup/webpage.
|
||||
"""The tag is missing from the soup/web-page.
|
||||
|
||||
Internal exception to mal_scraper.
|
||||
This is internal, so you should instead catch :class:`.ParseError`.
|
||||
"""
|
||||
|
||||
def __init__(self, tag=None):
|
||||
super().__init__('Missing from soup/webpage', tag)
|
||||
super().__init__('Missing from soup/web-page', tag)
|
||||
@@ -3,7 +3,6 @@
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
last_online_minutes = re.compile(r'(?P<minutes>\d+) minutes? ago')
|
||||
last_online_hours = re.compile(r'(?P<hours>\d+) hours? ago')
|
||||
|
||||
@@ -15,7 +14,7 @@ def get_datetime(text, relative_to=None):
|
||||
in case the timestamp was generated at a different time.
|
||||
|
||||
Args:
|
||||
text (str): The following examples are supported
|
||||
text (str): The following examples are supported (with varying accuracy)
|
||||
Oct 1, 2013 11:04 PM
|
||||
Oct 1, 4:29 AM
|
||||
Yesterday, 9:58 AM
|
||||
@@ -25,9 +24,11 @@ def get_datetime(text, relative_to=None):
|
||||
1 minute ago
|
||||
Now
|
||||
|
||||
Returns datetime.datetime
|
||||
Returns:
|
||||
datetime.datetime
|
||||
|
||||
Raises ValueError if the conversion fails
|
||||
Raises:
|
||||
ValueError if the conversion fails
|
||||
|
||||
Issues:
|
||||
- Potentially locale-dependent.
|
||||
@@ -72,16 +73,36 @@ def get_datetime(text, relative_to=None):
|
||||
|
||||
|
||||
def get_date(text):
|
||||
"""Convert a date like "Apr 3, 1998"
|
||||
"""Return a datetime from a date like "Apr 3, 1998", or None.
|
||||
|
||||
Args:
|
||||
text (str): like "Apr 3, 1998"
|
||||
text (str): The following examples are supported
|
||||
Apr 3, 1998
|
||||
Apr, 1994 (This will convert to 1st Apr 1994 as a best guess;
|
||||
https://myanimelist.net/anime/730)
|
||||
2003 (This will convert to 1st Jan 2003 as a best guess;
|
||||
https://myanimelist.net/anime/1190)
|
||||
|
||||
Returns datetime.date
|
||||
Returns:
|
||||
datetime.date
|
||||
|
||||
Raises ValueError if the conversion fails
|
||||
Raises:
|
||||
ValueError if the conversion fails
|
||||
|
||||
Issues:
|
||||
- This may be locale dependent
|
||||
This may be locale dependent
|
||||
"""
|
||||
return datetime.strptime(text, '%b %d, %Y').date()
|
||||
try:
|
||||
return datetime.strptime(text, '%b %d, %Y').date()
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
try:
|
||||
return datetime.strptime(text, '%b, %Y').date()
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
try:
|
||||
return datetime.strptime(text, '%Y').date()
|
||||
except ValueError:
|
||||
pass
|
||||
@@ -50,6 +50,31 @@ def discover_users(requester=request_passthrough):
|
||||
return users
|
||||
|
||||
|
||||
# TODO: Clean this up
|
||||
username_regex = re.compile(
|
||||
r"href=[\"'](https?\://myanimelist\.net)?/profile/(?P<username>\w+)[\w/]*[\"']",
|
||||
re.ASCII | re.DOTALL | re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def discover_users_from_html(html):
|
||||
"""Generate usernames from the given HTML (repetition is possible)
|
||||
|
||||
Args:
|
||||
html (str): HTML to hunt through
|
||||
|
||||
Yields:
|
||||
Usernames (string)
|
||||
|
||||
Test strings::
|
||||
|
||||
<a href="/profile/TheLlama">
|
||||
<a href="https://myanimelist.net/profile/TheLlama">
|
||||
<a href="/profile/TheLlama/reviews">All reviews</a>
|
||||
"""
|
||||
return (m.group('username') for m in username_regex.finditer(html))
|
||||
|
||||
|
||||
def get_user_stats(username, requester=request_passthrough):
|
||||
"""Return statistics about a particular user.
|
||||
|
||||
@@ -108,7 +133,7 @@ def get_user_anime_list(username, requester=request_passthrough):
|
||||
|
||||
{
|
||||
name: (string) name of the anime
|
||||
id_ref: (id_ref) can be used with retrieve_anime,
|
||||
id_ref: (id_ref) can be used with get_anime,
|
||||
consumption_status: (ConsumptionStatus),
|
||||
is_rewatch: (bool),
|
||||
score: (int) 0-10,
|
||||
@@ -145,7 +170,10 @@ def get_user_anime_list(username, requester=request_passthrough):
|
||||
|
||||
|
||||
def get_profile_url_from_username(username):
|
||||
return 'http://myanimelist.net/profile/{:s}'.format(username)
|
||||
# Use HTTPS to avoid auto-redirect from HTTP (except for tests)
|
||||
from .__init__ import FORCE_HTTP
|
||||
protocol = 'http' if FORCE_HTTP else 'https'
|
||||
return '{}://myanimelist.net/profile/{:s}'.format(protocol, username)
|
||||
|
||||
|
||||
def get_anime_list_url_for_user(username, offset=0):
|
||||
@@ -157,8 +185,10 @@ def get_anime_list_url_for_user(username, offset=0):
|
||||
|
||||
Returns: String url
|
||||
"""
|
||||
url = 'http://myanimelist.net/animelist/{username}/load.json?offset={offset:d}&status=7'
|
||||
return url.format(username=username, offset=offset)
|
||||
from .__init__ import FORCE_HTTP
|
||||
protocol = 'http' if FORCE_HTTP else 'https'
|
||||
url = '{protocol}://myanimelist.net/animelist/{username}/load.json?offset={offset:d}&status=7'
|
||||
return url.format(protocol=protocol, username=username, offset=offset)
|
||||
|
||||
|
||||
# --- Dynamic User Discovery ---
|
||||
|
||||
+1356
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+1015
File diff suppressed because it is too large.
Load diff
+1180
File diff suppressed because it is too large.
Load diff
+1074
File diff suppressed because it is too large.
Load diff
+1389
File diff suppressed because it is too large.
Load diff
@@ -91,6 +91,11 @@ class ResponsesWrapper:
|
||||
@pytest.yield_fixture(autouse=True)
|
||||
def mock_requests(request):
|
||||
"""Mock all requests unless the LIVE_RESPONSES environ has been set."""
|
||||
|
||||
# MAL URLs should be HTTP for mocking
|
||||
import mal_scraper.__init__
|
||||
mal_scraper.__init__.FORCE_HTTP = True
|
||||
|
||||
use_live = bool(os.environ.get('LIVE_RESPONSES', False))
|
||||
with responses.RequestsMock(assert_all_requests_are_fired=True) as rsps:
|
||||
yield ResponsesWrapper(rsps, use_live)
|
||||
@@ -7,18 +7,18 @@ import pytest
|
||||
import mal_scraper
|
||||
|
||||
|
||||
def test_download_first(mock_requests):
|
||||
def test_get_anime_successful(mock_requests):
|
||||
"""Can we retrieve the first show ever?"""
|
||||
mock_requests.optional_mock('http://myanimelist.net/anime/1')
|
||||
meta, info = mal_scraper.retrieve_anime(1)
|
||||
meta, info = mal_scraper.get_anime(1)
|
||||
|
||||
# Fuzzy match datetime
|
||||
assert datetime.utcnow() - meta['when'] < timedelta(seconds=30)
|
||||
|
||||
assert meta == {
|
||||
# Assert meta contained by ...
|
||||
assert meta.items() >= {
|
||||
'id_ref': 1,
|
||||
'when': meta['when'], # UTC Datetime
|
||||
}
|
||||
}.items()
|
||||
|
||||
assert info == {
|
||||
'name': 'Cowboy Bebop',
|
||||
@@ -26,8 +26,8 @@ def test_download_first(mock_requests):
|
||||
'format': mal_scraper.Format.tv,
|
||||
'episodes': 26, # None means unknown
|
||||
'airing_status': mal_scraper.AiringStatus.finished,
|
||||
'airing_started': date(year=1998, month=4, day=3), # None means unknown
|
||||
'airing_finished': date(year=1999, month=4, day=24), # None means unknown
|
||||
'airing_started': date(year=1998, month=4, day=3),
|
||||
'airing_finished': date(year=1999, month=4, day=24),
|
||||
'airing_premiere': (1998, mal_scraper.Season.spring),
|
||||
# 'age_rating': mal_scraper.AgeRating.restricted,
|
||||
# 'mal_score': 0,
|
||||
@@ -38,30 +38,79 @@ def test_download_first(mock_requests):
|
||||
}
|
||||
|
||||
|
||||
def test_download_first_fail(mock_requests):
|
||||
"""Do we get a failed success if the page was bad?"""
|
||||
def test_parsing_a_bad_page_raises_an_error(mock_requests):
|
||||
mock_requests.always_mock(
|
||||
'http://myanimelist.net/anime/1',
|
||||
'garbled_anime_page',
|
||||
)
|
||||
with pytest.raises(mal_scraper.ParseError):
|
||||
mal_scraper.retrieve_anime(1)
|
||||
mal_scraper.get_anime(1)
|
||||
|
||||
|
||||
def test_parsing_unknown_episodes(mock_requests):
|
||||
def test_parsing_name_english_that_is_missing(mock_requests):
|
||||
mock_requests.optional_mock('http://myanimelist.net/anime/15')
|
||||
meta, data = mal_scraper.get_anime(15)
|
||||
assert data['name_english'] == ''
|
||||
|
||||
|
||||
def test_parsing_episodes_that_is_unknown(mock_requests):
|
||||
"""Do we return None for an unknown number of episodes?"""
|
||||
mock_requests.always_mock(
|
||||
'http://myanimelist.net/anime/32105',
|
||||
'unknown_episodes',
|
||||
)
|
||||
|
||||
assert mal_scraper.retrieve_anime(32105)[1]['episodes'] is None
|
||||
assert mal_scraper.get_anime(32105)[1]['episodes'] is None
|
||||
|
||||
|
||||
def test_parsing_unknown_end_date(mock_requests):
|
||||
def test_parsing_airing_started_with_year_and_month_only(mock_requests):
|
||||
"""Do we return the year and month if the day is missing?"""
|
||||
mock_requests.optional_mock('http://myanimelist.net/anime/730')
|
||||
meta, data = mal_scraper.get_anime(730)
|
||||
assert data['airing_started'] == date(1994, 4, 1) # "Apr 1994"
|
||||
|
||||
|
||||
def test_parsing_airing_started_with_year_only(mock_requests):
|
||||
"""Do we return the year and month if the day is missing?"""
|
||||
mock_requests.optional_mock('http://myanimelist.net/anime/1190')
|
||||
meta, data = mal_scraper.get_anime(1190)
|
||||
assert data['airing_started'] == date(2003, 1, 1) # "2003"
|
||||
|
||||
|
||||
def test_parsing_end_date_that_is_unknown(mock_requests):
|
||||
mock_requests.always_mock(
|
||||
'http://myanimelist.net/anime/32105',
|
||||
'unknown_end_date',
|
||||
)
|
||||
assert mal_scraper.get_anime(32105)[1]['airing_finished'] is None
|
||||
|
||||
assert mal_scraper.retrieve_anime(32105)[1]['airing_finished'] is None
|
||||
|
||||
def test_parsing_airing_started_without_end_date(mock_requests):
|
||||
mock_requests.optional_mock('http://myanimelist.net/anime/5')
|
||||
meta, data = mal_scraper.get_anime(5)
|
||||
assert data['airing_started'] == date(2001, 9, 1)
|
||||
assert data['airing_finished'] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('id_ref', [
|
||||
5, # Film
|
||||
44, # OVA
|
||||
574, # ONA
|
||||
])
|
||||
def test_parsing_missing_premiere(mock_requests, id_ref):
|
||||
mock_requests.optional_mock('http://myanimelist.net/anime/%d' % id_ref)
|
||||
assert mal_scraper.get_anime(id_ref).data['airing_premiere'] is None
|
||||
|
||||
|
||||
def test_user_discovery_on_anime_page(mock_requests):
|
||||
mock_requests.optional_mock('http://myanimelist.net/anime/1')
|
||||
meta, info = mal_scraper.get_anime(1)
|
||||
|
||||
html = meta['response'].text
|
||||
usernames = list(mal_scraper.discover_users_from_html(html))
|
||||
assert usernames == [
|
||||
'TheLlama', 'TheLlama', 'TheLlama', 'TheLlama', 'Polyphemus',
|
||||
'Polyphemus', 'Polyphemus', 'Polyphemus', 'DeusAnima', 'DeusAnima',
|
||||
'DeusAnima', 'DeusAnima', 'TheCriticsClub', 'TheCriticsClub',
|
||||
'TheCriticsClub', 'TheCriticsClub', 'ElectricSlime', 'Mana', 'Scribbly',
|
||||
'Legg91', 'Metty', 'Darius', 'tokaicentral85', 'Ai_Sakura',
|
||||
]
|
||||
Reference in new issue
Block a user