opac-client 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- opac/__init__.py +13 -0
- opac/cli.py +166 -0
- opac/client.py +397 -0
- opac/models.py +51 -0
- opac/parser.py +224 -0
- opac/server.py +156 -0
- opac_client-1.0.0.dist-info/METADATA +814 -0
- opac_client-1.0.0.dist-info/RECORD +12 -0
- opac_client-1.0.0.dist-info/WHEEL +5 -0
- opac_client-1.0.0.dist-info/entry_points.txt +3 -0
- opac_client-1.0.0.dist-info/licenses/LICENSE +674 -0
- opac_client-1.0.0.dist-info/top_level.txt +1 -0
opac/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Cliente de búsqueda para catálogos web basados en AbsysNet Opac."""
|
|
2
|
+
|
|
3
|
+
from .client import OpacClient, OpacError
|
|
4
|
+
from .models import SearchQuery, SearchResult
|
|
5
|
+
from .models import SearchResults
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"OpacClient",
|
|
9
|
+
"OpacError",
|
|
10
|
+
"SearchQuery",
|
|
11
|
+
"SearchResult",
|
|
12
|
+
"SearchResults",
|
|
13
|
+
]
|
opac/cli.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Interfaz de línea de comandos para opac-client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Sequence
|
|
9
|
+
|
|
10
|
+
from .client import OpacClient, OpacError
|
|
11
|
+
from .models import SearchQuery, SearchResult
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
15
|
+
parser = argparse.ArgumentParser(
|
|
16
|
+
prog="opac",
|
|
17
|
+
description=(
|
|
18
|
+
"Busca libros, películas y otros recursos "
|
|
19
|
+
"en un catálogo AbsysNet Opac."
|
|
20
|
+
),
|
|
21
|
+
)
|
|
22
|
+
parser.add_argument(
|
|
23
|
+
"url",
|
|
24
|
+
help="URL del catálogo (p. ej. http://gestiona.comunidad.madrid/biblio_publicas/cgi-bin/abnetopac)",
|
|
25
|
+
)
|
|
26
|
+
parser.add_argument(
|
|
27
|
+
"keywords",
|
|
28
|
+
nargs="?",
|
|
29
|
+
default="",
|
|
30
|
+
help="Palabras clave",
|
|
31
|
+
)
|
|
32
|
+
parser.add_argument(
|
|
33
|
+
"--page", type=int, default=1, help="Página que se consultará"
|
|
34
|
+
)
|
|
35
|
+
parser.add_argument(
|
|
36
|
+
"--all",
|
|
37
|
+
dest="all_pages",
|
|
38
|
+
action="store_true",
|
|
39
|
+
help="Recorrer todas las páginas",
|
|
40
|
+
)
|
|
41
|
+
parser.add_argument(
|
|
42
|
+
"--max-pages",
|
|
43
|
+
type=int,
|
|
44
|
+
default=100,
|
|
45
|
+
help="Límite de páginas para --all",
|
|
46
|
+
)
|
|
47
|
+
parser.add_argument(
|
|
48
|
+
"--timeout",
|
|
49
|
+
type=float,
|
|
50
|
+
default=20.0,
|
|
51
|
+
help="Tiempo máximo de espera en segundos",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
parser.add_argument("--expert-search", dest="expert_any_field")
|
|
55
|
+
parser.add_argument("--title")
|
|
56
|
+
parser.add_argument("--author")
|
|
57
|
+
parser.add_argument("--editorial")
|
|
58
|
+
parser.add_argument("--subject")
|
|
59
|
+
parser.add_argument("--collection")
|
|
60
|
+
parser.add_argument("--genre")
|
|
61
|
+
parser.add_argument("--min-publish-date")
|
|
62
|
+
parser.add_argument("--max-publish-date")
|
|
63
|
+
parser.add_argument("--language")
|
|
64
|
+
parser.add_argument("--country")
|
|
65
|
+
parser.add_argument("--medium")
|
|
66
|
+
parser.add_argument("--sort-by")
|
|
67
|
+
parser.add_argument("--items-per-page", type=int, default=100)
|
|
68
|
+
parser.add_argument(
|
|
69
|
+
"--json", action="store_true", help="Imprimir resultados como JSON"
|
|
70
|
+
)
|
|
71
|
+
return parser
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _query_from_args(args: argparse.Namespace) -> SearchQuery:
|
|
75
|
+
return SearchQuery(
|
|
76
|
+
normal_any_field=args.keywords or None,
|
|
77
|
+
expert_any_field=args.expert_any_field,
|
|
78
|
+
title=args.title,
|
|
79
|
+
author=args.author,
|
|
80
|
+
editorial=args.editorial,
|
|
81
|
+
subject=args.subject,
|
|
82
|
+
collection=args.collection,
|
|
83
|
+
genre=args.genre,
|
|
84
|
+
min_publish_date=args.min_publish_date,
|
|
85
|
+
max_publish_date=args.max_publish_date,
|
|
86
|
+
language=args.language,
|
|
87
|
+
country=args.country,
|
|
88
|
+
medium=args.medium,
|
|
89
|
+
sort_by=args.sort_by or "56297072",
|
|
90
|
+
items_per_page=args.items_per_page,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _print_result(item: SearchResult, index: int) -> None:
|
|
95
|
+
kind = item.resource_type or "Recurso"
|
|
96
|
+
print(f"{index}. {item.title} [{kind}]")
|
|
97
|
+
if item.author:
|
|
98
|
+
print(f" Autoría: {item.author}")
|
|
99
|
+
if item.year:
|
|
100
|
+
print(f" Año: {item.year}")
|
|
101
|
+
if item.language:
|
|
102
|
+
print(f" Idioma: {item.language}")
|
|
103
|
+
if item.titn:
|
|
104
|
+
print(f" Número de registro: {item.titn}")
|
|
105
|
+
if item.description:
|
|
106
|
+
print(f" {item.description}")
|
|
107
|
+
if item.cover_url:
|
|
108
|
+
print(f" Cubierta: {item.cover_url}")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
112
|
+
"""Punto de entrada del comando `opac`."""
|
|
113
|
+
args = _build_parser().parse_args(argv)
|
|
114
|
+
query = _query_from_args(args)
|
|
115
|
+
try:
|
|
116
|
+
client = OpacClient(args.url, timeout=args.timeout)
|
|
117
|
+
if args.all_pages:
|
|
118
|
+
items = client.search_all(
|
|
119
|
+
query,
|
|
120
|
+
max_pages=args.max_pages,
|
|
121
|
+
)
|
|
122
|
+
page_result = None
|
|
123
|
+
else:
|
|
124
|
+
page_result = client.search(
|
|
125
|
+
query,
|
|
126
|
+
page=args.page,
|
|
127
|
+
)
|
|
128
|
+
items = page_result.items
|
|
129
|
+
except (OpacError, TypeError, ValueError) as exc:
|
|
130
|
+
print(f"Opac: {exc}", file=sys.stderr)
|
|
131
|
+
return 2
|
|
132
|
+
|
|
133
|
+
if args.json:
|
|
134
|
+
payload: dict[str, object] = {
|
|
135
|
+
"items": [_result_to_dict(item) for item in items]
|
|
136
|
+
}
|
|
137
|
+
if page_result is not None:
|
|
138
|
+
payload.update(
|
|
139
|
+
current_page=page_result.current_page,
|
|
140
|
+
page_numbers=page_result.page_numbers,
|
|
141
|
+
next_page_url=page_result.next_page_url,
|
|
142
|
+
)
|
|
143
|
+
else:
|
|
144
|
+
payload["all_pages"] = True
|
|
145
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
146
|
+
return 0
|
|
147
|
+
|
|
148
|
+
if not items:
|
|
149
|
+
print("No se encontraron recursos.")
|
|
150
|
+
else:
|
|
151
|
+
for index, item in enumerate(items, start=1):
|
|
152
|
+
_print_result(item, index)
|
|
153
|
+
if page_result and page_result.next_page_url:
|
|
154
|
+
print(f"Página siguiente: {page_result.next_page_url}")
|
|
155
|
+
if args.all_pages:
|
|
156
|
+
print(f"Total de recursos recuperados: {len(items)}")
|
|
157
|
+
return 0
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _result_to_dict(item: SearchResult) -> dict[str, object]:
|
|
161
|
+
"""Serializa los campos del modelo de resultado a un objeto JSON."""
|
|
162
|
+
return item._asdict()
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
if __name__ == "__main__":
|
|
166
|
+
raise SystemExit(main())
|
opac/client.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"""Cliente HTTP de solo lectura para búsquedas en catálogos AbsysNet Opac."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from html.parser import HTMLParser
|
|
6
|
+
from http.cookiejar import CookieJar
|
|
7
|
+
import re
|
|
8
|
+
from urllib.error import HTTPError, URLError
|
|
9
|
+
from urllib.parse import parse_qs, urlencode, urljoin, urlsplit, urlunsplit
|
|
10
|
+
from urllib.request import (
|
|
11
|
+
HTTPRedirectHandler,
|
|
12
|
+
HTTPCookieProcessor,
|
|
13
|
+
Request,
|
|
14
|
+
build_opener,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
from .models import SearchQuery, SearchResult, SearchResults
|
|
18
|
+
from .parser import parse_search_results
|
|
19
|
+
from types import MappingProxyType
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
MAP_PARAM = MappingProxyType({
|
|
23
|
+
"normal_any_field": "xsqf01",
|
|
24
|
+
"expert_any_field": "xsqf99",
|
|
25
|
+
"title": "xsqf02",
|
|
26
|
+
"author": "xsqf03",
|
|
27
|
+
"editorial": "xsqf04",
|
|
28
|
+
"subject": "xsqf05",
|
|
29
|
+
"collection": "xsqf06",
|
|
30
|
+
"genre": "xsqf09",
|
|
31
|
+
"min_publish_date": "xsqf07",
|
|
32
|
+
"max_publish_date": "xsqf08",
|
|
33
|
+
"language": "select01",
|
|
34
|
+
"country": "select02",
|
|
35
|
+
"medium": "select03",
|
|
36
|
+
"sort_by": "xssort",
|
|
37
|
+
"items_per_page": "xsnlis",
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _RedirectHandler(HTTPRedirectHandler):
|
|
42
|
+
"""Permite cadenas largas de redirecciones, evitando ciclos infinitos."""
|
|
43
|
+
|
|
44
|
+
max_redirections = 50
|
|
45
|
+
max_repeats = 10
|
|
46
|
+
|
|
47
|
+
def redirect_request(
|
|
48
|
+
self,
|
|
49
|
+
req: Request,
|
|
50
|
+
fp: object,
|
|
51
|
+
code: int,
|
|
52
|
+
msg: str,
|
|
53
|
+
headers: object,
|
|
54
|
+
newurl: str,
|
|
55
|
+
) -> Request | None:
|
|
56
|
+
redirected = super().redirect_request(
|
|
57
|
+
req, fp, code, msg, headers, newurl
|
|
58
|
+
)
|
|
59
|
+
if redirected is not None:
|
|
60
|
+
referer = _referer_header(req.full_url, newurl)
|
|
61
|
+
if referer:
|
|
62
|
+
redirected.add_unredirected_header("Referer", referer)
|
|
63
|
+
return redirected
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _referer_header(source_url: str, target_url: str) -> str | None:
|
|
67
|
+
"""Devuelve un Referer seguro, siguiendo la política web habitual."""
|
|
68
|
+
source = urlsplit(source_url)
|
|
69
|
+
target = urlsplit(target_url)
|
|
70
|
+
is_https_downgrade = (
|
|
71
|
+
source.scheme.casefold() == "https"
|
|
72
|
+
and target.scheme.casefold() != "https"
|
|
73
|
+
)
|
|
74
|
+
if is_https_downgrade:
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
hostname = source.hostname or ""
|
|
78
|
+
if ":" in hostname:
|
|
79
|
+
hostname = f"[{hostname}]"
|
|
80
|
+
port = source.port
|
|
81
|
+
netloc = hostname
|
|
82
|
+
if port is not None:
|
|
83
|
+
netloc += f":{port}"
|
|
84
|
+
origin = f"{source.scheme}://{netloc}"
|
|
85
|
+
|
|
86
|
+
source_port = port or (443 if source.scheme.casefold() == "https" else 80)
|
|
87
|
+
target_port = target.port or (
|
|
88
|
+
443 if target.scheme.casefold() == "https" else 80
|
|
89
|
+
)
|
|
90
|
+
same_origin = (
|
|
91
|
+
source.scheme.casefold() == target.scheme.casefold()
|
|
92
|
+
and (source.hostname or "").casefold()
|
|
93
|
+
== (target.hostname or "").casefold()
|
|
94
|
+
and source_port == target_port
|
|
95
|
+
)
|
|
96
|
+
if same_origin:
|
|
97
|
+
return urlunsplit(
|
|
98
|
+
(source.scheme, netloc, source.path, source.query, "")
|
|
99
|
+
)
|
|
100
|
+
return origin
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class _MetaRefreshParser(HTMLParser):
|
|
104
|
+
"""Extrae el destino de una redirección HTML ``meta refresh``."""
|
|
105
|
+
|
|
106
|
+
_refresh_pattern = re.compile(
|
|
107
|
+
r"^\s*\d+(?:\.\d+)?\s*;\s*url\s*=\s*(.*?)\s*$",
|
|
108
|
+
re.IGNORECASE,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
def __init__(self) -> None:
|
|
112
|
+
super().__init__(convert_charrefs=True)
|
|
113
|
+
self.target: str | None = None
|
|
114
|
+
|
|
115
|
+
def handle_starttag(
|
|
116
|
+
self, tag: str, attrs: list[tuple[str, str | None]]
|
|
117
|
+
) -> None:
|
|
118
|
+
if tag.casefold() != "meta":
|
|
119
|
+
return
|
|
120
|
+
values = {key.casefold(): value or "" for key, value in attrs}
|
|
121
|
+
if values.get("http-equiv", "").strip().casefold() != "refresh":
|
|
122
|
+
return
|
|
123
|
+
match = self._refresh_pattern.fullmatch(values.get("content", ""))
|
|
124
|
+
if match:
|
|
125
|
+
self.target = match.group(1).strip().strip("\"'")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class _SearchFormParser(HTMLParser):
|
|
129
|
+
"""Lee la acción y los campos ocultos del formulario de búsqueda."""
|
|
130
|
+
|
|
131
|
+
def __init__(self) -> None:
|
|
132
|
+
super().__init__(convert_charrefs=True)
|
|
133
|
+
self.action: str | None = None
|
|
134
|
+
self.method = "get"
|
|
135
|
+
self.hidden_fields: dict[str, str] = {}
|
|
136
|
+
self._inside_search_form = False
|
|
137
|
+
|
|
138
|
+
def handle_starttag(
|
|
139
|
+
self, tag: str, attrs: list[tuple[str, str | None]]
|
|
140
|
+
) -> None:
|
|
141
|
+
values = {key.casefold(): value or "" for key, value in attrs}
|
|
142
|
+
if tag.casefold() == "form":
|
|
143
|
+
self._inside_search_form = values.get("id") == "abnformSearch"
|
|
144
|
+
if self._inside_search_form:
|
|
145
|
+
self.action = values.get("action") or None
|
|
146
|
+
self.method = values.get("method", "get").casefold()
|
|
147
|
+
return
|
|
148
|
+
if not self._inside_search_form or tag.casefold() != "input":
|
|
149
|
+
return
|
|
150
|
+
if values.get("type", "").casefold() != "hidden":
|
|
151
|
+
return
|
|
152
|
+
name = values.get("name")
|
|
153
|
+
if name:
|
|
154
|
+
self.hidden_fields[name] = values.get("value", "")
|
|
155
|
+
|
|
156
|
+
def handle_endtag(self, tag: str) -> None:
|
|
157
|
+
if tag.casefold() == "form" and self._inside_search_form:
|
|
158
|
+
self._inside_search_form = False
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class OpacError(Exception):
|
|
162
|
+
"""Error de red o de respuesta del catálogo."""
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class OpacClient:
|
|
166
|
+
"""Busca recursos en un sitio compatible con el catálogo AbsysNet Opac.
|
|
167
|
+
|
|
168
|
+
Ejemplo::
|
|
169
|
+
|
|
170
|
+
client = OpacClient(
|
|
171
|
+
"https://gestiona.comunidad.madrid/biblio_publicas/"
|
|
172
|
+
"cgi-bin/abnetopac"
|
|
173
|
+
)
|
|
174
|
+
query = SearchQuery(keywords="Mabuse", language="spa", nature="ebook")
|
|
175
|
+
results = client.search(query)
|
|
176
|
+
for item in results.items:
|
|
177
|
+
print(item.title, item.authors, item.url)
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
def __init__(
|
|
181
|
+
self,
|
|
182
|
+
url: str,
|
|
183
|
+
*,
|
|
184
|
+
timeout: float = 20.0,
|
|
185
|
+
user_agent: str = "opac-client/0.1 (+https://www.python.org/)",
|
|
186
|
+
) -> None:
|
|
187
|
+
parsed = urlsplit(url.strip())
|
|
188
|
+
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
|
189
|
+
raise ValueError("La URL debe ser absoluta y usar http o https.")
|
|
190
|
+
if timeout <= 0:
|
|
191
|
+
raise ValueError("timeout debe ser mayor que cero.")
|
|
192
|
+
self._base_url = url
|
|
193
|
+
self._timeout = timeout
|
|
194
|
+
self._user_agent = user_agent
|
|
195
|
+
self._cookies = CookieJar()
|
|
196
|
+
self._opener = build_opener(
|
|
197
|
+
_RedirectHandler(),
|
|
198
|
+
HTTPCookieProcessor(self._cookies),
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
def get_bytes(self, mlkob: str) -> bytes:
|
|
202
|
+
"""Descarga el contenido asociado a un identificador ``MLKOB``."""
|
|
203
|
+
if not mlkob:
|
|
204
|
+
raise ValueError("mlkob no puede estar vacío.")
|
|
205
|
+
|
|
206
|
+
_, landing_url = self._fetch(self._base_url)
|
|
207
|
+
parsed_url = urlsplit(landing_url)
|
|
208
|
+
content_url = urlunsplit(
|
|
209
|
+
(
|
|
210
|
+
parsed_url.scheme,
|
|
211
|
+
parsed_url.netloc,
|
|
212
|
+
parsed_url.path,
|
|
213
|
+
urlencode({"ACC": "299", "MLKOB": mlkob}),
|
|
214
|
+
"",
|
|
215
|
+
)
|
|
216
|
+
)
|
|
217
|
+
content, _, _ = self._fetch_raw(
|
|
218
|
+
content_url,
|
|
219
|
+
referer=landing_url,
|
|
220
|
+
#accept="image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
|
|
221
|
+
)
|
|
222
|
+
return content
|
|
223
|
+
|
|
224
|
+
def _fetch(
|
|
225
|
+
self,
|
|
226
|
+
url: str,
|
|
227
|
+
*,
|
|
228
|
+
data: bytes | None = None,
|
|
229
|
+
referer: str | None = None,
|
|
230
|
+
) -> tuple[str, str]:
|
|
231
|
+
content, final_url, charset = self._fetch_raw(
|
|
232
|
+
url, data=data, referer=referer
|
|
233
|
+
)
|
|
234
|
+
return content.decode(charset, errors="replace"), final_url
|
|
235
|
+
|
|
236
|
+
def _fetch_raw(
|
|
237
|
+
self,
|
|
238
|
+
url: str,
|
|
239
|
+
*,
|
|
240
|
+
data: bytes | None = None,
|
|
241
|
+
referer: str | None = None,
|
|
242
|
+
accept: str = "text/html,application/xhtml+xml",
|
|
243
|
+
) -> tuple[bytes, str, str]:
|
|
244
|
+
"""Obtiene bytes sin alterar el cuerpo y sigue redirecciones."""
|
|
245
|
+
current_url = url
|
|
246
|
+
referer_url = referer
|
|
247
|
+
request_data = data
|
|
248
|
+
visited: set[str] = set()
|
|
249
|
+
meta_refreshes = 0
|
|
250
|
+
while True:
|
|
251
|
+
if current_url in visited:
|
|
252
|
+
raise OpacError(
|
|
253
|
+
"Bucle de redirección detectado al consultar "
|
|
254
|
+
f"{current_url}."
|
|
255
|
+
)
|
|
256
|
+
visited.add(current_url)
|
|
257
|
+
request = Request(
|
|
258
|
+
current_url,
|
|
259
|
+
data=request_data,
|
|
260
|
+
headers={
|
|
261
|
+
"User-Agent": self._user_agent,
|
|
262
|
+
"Accept": accept,
|
|
263
|
+
},
|
|
264
|
+
)
|
|
265
|
+
if request_data is not None:
|
|
266
|
+
request.add_header(
|
|
267
|
+
"Content-Type", "application/x-www-form-urlencoded"
|
|
268
|
+
)
|
|
269
|
+
if referer_url:
|
|
270
|
+
referer = _referer_header(referer_url, current_url)
|
|
271
|
+
if referer:
|
|
272
|
+
request.add_unredirected_header("Referer", referer)
|
|
273
|
+
try:
|
|
274
|
+
with self._opener.open(
|
|
275
|
+
request, timeout=self._timeout
|
|
276
|
+
) as response:
|
|
277
|
+
charset = (
|
|
278
|
+
response.headers.get_content_charset() or "utf-8"
|
|
279
|
+
)
|
|
280
|
+
content = response.read()
|
|
281
|
+
final_url = response.geturl()
|
|
282
|
+
except (HTTPError, URLError, OSError) as exc:
|
|
283
|
+
raise OpacError(
|
|
284
|
+
f"No se pudo consultar {current_url}: {exc}"
|
|
285
|
+
) from exc
|
|
286
|
+
request_data = None
|
|
287
|
+
|
|
288
|
+
refresh = _MetaRefreshParser()
|
|
289
|
+
refresh.feed(content.decode(charset, errors="replace"))
|
|
290
|
+
if not refresh.target:
|
|
291
|
+
return content, final_url, charset
|
|
292
|
+
meta_refreshes += 1
|
|
293
|
+
if meta_refreshes > 50:
|
|
294
|
+
raise OpacError(
|
|
295
|
+
"Se superó el límite de 50 redirecciones HTML."
|
|
296
|
+
)
|
|
297
|
+
referer_url = final_url
|
|
298
|
+
current_url = urljoin(final_url, refresh.target)
|
|
299
|
+
|
|
300
|
+
def search(
|
|
301
|
+
self,
|
|
302
|
+
query: SearchQuery,
|
|
303
|
+
*,
|
|
304
|
+
page: int = 1,
|
|
305
|
+
) -> SearchResults:
|
|
306
|
+
"""Ejecuta una búsqueda y devuelve los recursos de la página indicada.
|
|
307
|
+
|
|
308
|
+
Los términos y filtros se especifican en un ``SearchQuery``.
|
|
309
|
+
"""
|
|
310
|
+
if not isinstance(query, SearchQuery):
|
|
311
|
+
raise TypeError("query debe ser una instancia de SearchQuery.")
|
|
312
|
+
if page < 1:
|
|
313
|
+
raise ValueError("page debe ser un entero positivo.")
|
|
314
|
+
|
|
315
|
+
landing_html, landing_url = self._fetch(self._base_url)
|
|
316
|
+
form = _SearchFormParser()
|
|
317
|
+
form.feed(landing_html)
|
|
318
|
+
if not form.action:
|
|
319
|
+
raise OpacError(
|
|
320
|
+
"No se encontró el formulario de búsqueda abnformSearch."
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
fields = dict(form.hidden_fields)
|
|
324
|
+
fields.update(
|
|
325
|
+
{
|
|
326
|
+
MAP_PARAM[name]: str(value)
|
|
327
|
+
for name, value in query._asdict().items()
|
|
328
|
+
if value not in (None, "")
|
|
329
|
+
}
|
|
330
|
+
)
|
|
331
|
+
request_url = urljoin(landing_url, form.action)
|
|
332
|
+
if form.method == "post":
|
|
333
|
+
html, final_url = self._fetch(
|
|
334
|
+
request_url,
|
|
335
|
+
data=urlencode(fields).encode("utf-8"),
|
|
336
|
+
referer=landing_url,
|
|
337
|
+
)
|
|
338
|
+
else:
|
|
339
|
+
separator = "&" if urlsplit(request_url).query else "?"
|
|
340
|
+
html, final_url = self._fetch(
|
|
341
|
+
f"{request_url}{separator}{urlencode(fields)}",
|
|
342
|
+
referer=landing_url,
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
if page > 1:
|
|
346
|
+
result = urlsplit(final_url)
|
|
347
|
+
path = result.path.removesuffix("/NT1")
|
|
348
|
+
page_start = (page - 1) * max(query.items_per_page or 100, 1) + 1
|
|
349
|
+
page_url = urlunsplit(
|
|
350
|
+
(
|
|
351
|
+
result.scheme,
|
|
352
|
+
result.netloc,
|
|
353
|
+
path,
|
|
354
|
+
urlencode({"ACC": "161", "DOC": page_start}),
|
|
355
|
+
"",
|
|
356
|
+
)
|
|
357
|
+
)
|
|
358
|
+
html, final_url = self._fetch(page_url, referer=final_url)
|
|
359
|
+
|
|
360
|
+
parsed = parse_search_results(html, final_url)
|
|
361
|
+
next_page_url = parsed.next_page_url
|
|
362
|
+
return SearchResults(
|
|
363
|
+
items=parsed.items,
|
|
364
|
+
current_page=(
|
|
365
|
+
parsed.current_page
|
|
366
|
+
if parsed.current_page > 1 or page == 1
|
|
367
|
+
else page
|
|
368
|
+
),
|
|
369
|
+
page_numbers=parsed.page_numbers,
|
|
370
|
+
next_page_url=next_page_url,
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
def search_all(
|
|
374
|
+
self,
|
|
375
|
+
query: SearchQuery,
|
|
376
|
+
*,
|
|
377
|
+
max_pages: int = 100,
|
|
378
|
+
) -> tuple[SearchResult, ...]:
|
|
379
|
+
"""Recorre páginas siguientes hasta el final o ``max_pages``."""
|
|
380
|
+
if max_pages < 1:
|
|
381
|
+
raise ValueError("max_pages debe ser un entero positivo.")
|
|
382
|
+
results: list[SearchResult] = []
|
|
383
|
+
page = 1
|
|
384
|
+
while page <= max_pages:
|
|
385
|
+
current = self.search(query, page=page)
|
|
386
|
+
results.extend(current.items)
|
|
387
|
+
if not current.next_page_url:
|
|
388
|
+
break
|
|
389
|
+
next_page = parse_qs(
|
|
390
|
+
urlsplit(current.next_page_url).query
|
|
391
|
+
).get("page", [])
|
|
392
|
+
page = (
|
|
393
|
+
int(next_page[0])
|
|
394
|
+
if next_page and next_page[0].isdigit()
|
|
395
|
+
else page + 1
|
|
396
|
+
)
|
|
397
|
+
return tuple(results)
|
opac/models.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Modelos inmutables de datos devueltos por el cliente."""
|
|
2
|
+
|
|
3
|
+
from typing import NamedTuple, Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SearchResult(NamedTuple):
|
|
7
|
+
"""Un libro, película u otro recurso del catálogo."""
|
|
8
|
+
url: str
|
|
9
|
+
# span.js-T245
|
|
10
|
+
title: str
|
|
11
|
+
# span.span.js-TITN
|
|
12
|
+
titn: int
|
|
13
|
+
# span.js-T1XX
|
|
14
|
+
author: Optional[str] = None
|
|
15
|
+
# span.js-LENG
|
|
16
|
+
language: Optional[str] = None
|
|
17
|
+
# span.js-FEPU
|
|
18
|
+
year: Optional[int] = None
|
|
19
|
+
# span.c-docs_mat.m-docs_mat.i
|
|
20
|
+
resource_type: Optional[str] = None
|
|
21
|
+
# span.js-T520
|
|
22
|
+
description: Optional[str] = None
|
|
23
|
+
# span.c-docs_imgPreLoad img
|
|
24
|
+
cover_url: Optional[str] = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class SearchResults(NamedTuple):
|
|
28
|
+
"""Página de resultados e información para continuar la paginación."""
|
|
29
|
+
|
|
30
|
+
items: tuple[SearchResult, ...]
|
|
31
|
+
current_page: int = 1
|
|
32
|
+
page_numbers: tuple[int, ...] = ()
|
|
33
|
+
next_page_url: str | None = None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class SearchQuery(NamedTuple):
|
|
37
|
+
normal_any_field: Optional[str] = None
|
|
38
|
+
expert_any_field: Optional[str] = None
|
|
39
|
+
title: Optional[str] = None
|
|
40
|
+
author: Optional[str] = None
|
|
41
|
+
editorial: Optional[str] = None
|
|
42
|
+
subject: Optional[str] = None
|
|
43
|
+
collection: Optional[str] = None
|
|
44
|
+
genre: Optional[str] = None
|
|
45
|
+
min_publish_date: Optional[str] = None
|
|
46
|
+
max_publish_date: Optional[str] = None
|
|
47
|
+
language: Optional[str] = None
|
|
48
|
+
country: Optional[str] = None
|
|
49
|
+
medium: Optional[str] = None
|
|
50
|
+
sort_by: Optional[str] = "56297072" # Relevancia
|
|
51
|
+
items_per_page: Optional[int] = 100
|