yklibpy 0.1.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.
- yklibpy/__init__.py +17 -0
- yklibpy/common/__init__.py +15 -0
- yklibpy/common/convert_yaml_strip_tags.py +102 -0
- yklibpy/common/env.py +109 -0
- yklibpy/common/info.py +24 -0
- yklibpy/common/util.py +419 -0
- yklibpy/db/__init__.py +27 -0
- yklibpy/db/db_base.py +6 -0
- yklibpy/db/db_yaml.py +61 -0
- yklibpy/htmlparser/__init__.py +37 -0
- yklibpy/htmlparser/amazon.py +3 -0
- yklibpy/htmlparser/amazonsavedcartscraper.py +106 -0
- yklibpy/htmlparser/app.py +101 -0
- yklibpy/htmlparser/ascraper.py +77 -0
- yklibpy/htmlparser/configprepare.py +29 -0
- yklibpy/htmlparser/fanzadoujinpurchasedscraper.py +80 -0
- yklibpy/htmlparser/fanzadoujinscraper.py +235 -0
- yklibpy/htmlparser/h3scraper.py +68 -0
- yklibpy/htmlparser/htmlop.py +107 -0
- yklibpy/htmlparser/kuscraper.py +68 -0
- yklibpy/htmlparser/preparex.py +152 -0
- yklibpy/htmlparser/progress.py +36 -0
- yklibpy/htmlparser/py.typed +0 -0
- yklibpy/htmlparser/scraper.py +181 -0
- yklibpy/htmlparser/udemyscraper.py +224 -0
- yklibpy/tomlop/__init__.py +17 -0
- yklibpy/tomlop/tomlop.py +374 -0
- yklibpy-0.1.0.dist-info/METADATA +20 -0
- yklibpy-0.1.0.dist-info/RECORD +31 -0
- yklibpy-0.1.0.dist-info/WHEEL +4 -0
- yklibpy-0.1.0.dist-info/entry_points.txt +10 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Dict, List, Optional
|
|
3
|
+
|
|
4
|
+
from bs4 import BeautifulSoup
|
|
5
|
+
from ..common.info import Info
|
|
6
|
+
from ..common.util import Util
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Scraper:
|
|
10
|
+
def __init__(self):
|
|
11
|
+
"""Initialize in-memory containers for links and bookkeeping.
|
|
12
|
+
|
|
13
|
+
Returns:
|
|
14
|
+
None
|
|
15
|
+
"""
|
|
16
|
+
self.links_list = []
|
|
17
|
+
self.links_assoc = {}
|
|
18
|
+
self.info = {}
|
|
19
|
+
self.append_count = 0
|
|
20
|
+
self.no_append_count = 0
|
|
21
|
+
|
|
22
|
+
def _extract_links_assoc_from_info(self, info: Info) -> List[Dict[str, str]]:
|
|
23
|
+
"""Populate the associative map keyed by course ID.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
info (Info): Parsed HTML payload for a file.
|
|
27
|
+
|
|
28
|
+
Returns:
|
|
29
|
+
dict: ``links_assoc`` containing course records.
|
|
30
|
+
"""
|
|
31
|
+
self.scrape(info)
|
|
32
|
+
return self.links_assoc
|
|
33
|
+
|
|
34
|
+
def _extract_links_from_info(self, info: Info) -> List[Dict[str, str]]:
|
|
35
|
+
"""Base stub that child classes override to populate ``links_list``.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
info (Info): Parsed HTML context for the current file.
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
List[Dict[str, str]]: Defaults to an empty list.
|
|
42
|
+
"""
|
|
43
|
+
self.links_list = []
|
|
44
|
+
return self.links_list
|
|
45
|
+
|
|
46
|
+
def _parse_html_file(self, file_path: Path) -> Optional[BeautifulSoup]:
|
|
47
|
+
"""Read an HTML file and parse it into BeautifulSoup.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
file_path (Path): Path to the HTML file on disk.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
BeautifulSoup | None: Parsed DOM on success, otherwise ``None`` when
|
|
54
|
+
the file is missing or parsing fails.
|
|
55
|
+
"""
|
|
56
|
+
try:
|
|
57
|
+
encoding = Util.detect_encoding(file_path)
|
|
58
|
+
if encoding is None:
|
|
59
|
+
encoding = "utf-8"
|
|
60
|
+
|
|
61
|
+
with file_path.open("r", encoding=encoding) as f:
|
|
62
|
+
# Create a BeautifulSoup object using the lxml parser
|
|
63
|
+
# soup = BeautifulSoup(f, 'lxml')
|
|
64
|
+
soup = BeautifulSoup(f, "html5lib")
|
|
65
|
+
return soup
|
|
66
|
+
except FileNotFoundError:
|
|
67
|
+
print(f"Error: The file at {file_path} was not found.")
|
|
68
|
+
return None
|
|
69
|
+
except Exception as e:
|
|
70
|
+
print(f"An error occurred: {e}")
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
def scrape(self, url: str):
|
|
74
|
+
"""Primary scraping entry point; implemented by subclasses.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
url (str): Resource identifier or file hint.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
None
|
|
81
|
+
"""
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
def get_links_assoc_from_html(self, file_path: Path) -> List[Dict[str, str]]:
|
|
85
|
+
"""Parse an HTML file and return the associative course map.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
file_path (Path): Location of the HTML snapshot.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
dict: ``links_assoc`` entries derived from the file.
|
|
92
|
+
"""
|
|
93
|
+
assoc = {}
|
|
94
|
+
if file_path not in self.info.keys():
|
|
95
|
+
soup = self._parse_html_file(file_path)
|
|
96
|
+
if soup:
|
|
97
|
+
info = Info(file_path, file_path.name, soup, 0, 0)
|
|
98
|
+
self.info[file_path.name] = info
|
|
99
|
+
assoc = self._extract_links_assoc_from_info(info)
|
|
100
|
+
return assoc
|
|
101
|
+
|
|
102
|
+
def get_links_from_html(self, file_path: Path) -> List[Dict[str, str]]:
|
|
103
|
+
"""Parse an HTML file and return a list of course records.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
file_path (Path): Location of the HTML snapshot.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
List[Dict[str, str]]: Extracted course entries.
|
|
110
|
+
"""
|
|
111
|
+
links = []
|
|
112
|
+
if file_path not in self.info.keys():
|
|
113
|
+
soup = self._parse_html_file(file_path)
|
|
114
|
+
if soup:
|
|
115
|
+
info = Info(file_path, file_path.name, soup, 0, 0)
|
|
116
|
+
self.info[file_path.name] = info
|
|
117
|
+
links = self._extract_links_from_info(info)
|
|
118
|
+
return links
|
|
119
|
+
|
|
120
|
+
def _extract_links_from_info(self, info: Info) -> List[Dict[str, str]]:
|
|
121
|
+
links_list = self.scrape(info)
|
|
122
|
+
return links_list
|
|
123
|
+
|
|
124
|
+
def find_status_span_ancestors(self, soup: BeautifulSoup):
|
|
125
|
+
"""Locate role=\"status\" spans and dump their ancestor structure.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
soup (BeautifulSoup): Parsed HTML document.
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
list: Result from :meth:`find_item_ancestors`.
|
|
132
|
+
"""
|
|
133
|
+
status_spans = soup.find_all("span", role="status")
|
|
134
|
+
return self.find_item_ancestors(status_spans)
|
|
135
|
+
|
|
136
|
+
def find_item_ancestors(self, items: List[Dict[str, any]]):
|
|
137
|
+
"""Traverse ancestor chains for the supplied elements and log details.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
items (List[Dict[str, any]]): Result set (e.g., BeautifulSoup nodes)
|
|
141
|
+
whose parent hierarchy should be inspected.
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
list: Currently an empty list placeholder for future aggregation.
|
|
145
|
+
"""
|
|
146
|
+
for i, item in enumerate(items, 1):
|
|
147
|
+
|
|
148
|
+
# 祖先要素をすべて取得
|
|
149
|
+
ancestors = []
|
|
150
|
+
current = item.parent
|
|
151
|
+
level = 1
|
|
152
|
+
|
|
153
|
+
while current and current.name != "html":
|
|
154
|
+
assoc = {
|
|
155
|
+
"level": level,
|
|
156
|
+
"tag": current.name,
|
|
157
|
+
"text": current.get_text(strip=True)[:100] + "..."
|
|
158
|
+
if len(current.get_text(strip=True)) > 100
|
|
159
|
+
else current.get_text(strip=True),
|
|
160
|
+
"class": current.get("class", []),
|
|
161
|
+
"id": current.get("id", ""),
|
|
162
|
+
}
|
|
163
|
+
ancestors.append(assoc)
|
|
164
|
+
if "item" in assoc["class"]:
|
|
165
|
+
break
|
|
166
|
+
|
|
167
|
+
current = current.parent
|
|
168
|
+
level += 1
|
|
169
|
+
|
|
170
|
+
'''
|
|
171
|
+
for ancestor in ancestors:
|
|
172
|
+
indent = " " * ancestor["level"]
|
|
173
|
+
print(f"{indent}Level {ancestor['level']}: <{ancestor['tag']}>")
|
|
174
|
+
print(f"{indent} Text: {ancestor['text']}")
|
|
175
|
+
print(f"{indent} Class: {ancestor['class']}")
|
|
176
|
+
print(f"{indent} ID: {ancestor['id']}")
|
|
177
|
+
|
|
178
|
+
print("-" * 50)
|
|
179
|
+
'''
|
|
180
|
+
|
|
181
|
+
return []
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
from typing import Dict, List
|
|
2
|
+
from urllib.parse import parse_qs, urlparse
|
|
3
|
+
|
|
4
|
+
from bs4 import BeautifulSoup
|
|
5
|
+
from ..common.info import Info
|
|
6
|
+
from .progress import Progress
|
|
7
|
+
from .scraper import Scraper
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class UdemyScraper(Scraper):
|
|
11
|
+
def __init__(self):
|
|
12
|
+
"""Initialize Udemy-specific scraper state.
|
|
13
|
+
|
|
14
|
+
Returns:
|
|
15
|
+
None
|
|
16
|
+
"""
|
|
17
|
+
super().__init__()
|
|
18
|
+
|
|
19
|
+
def scrape(self, info: Info) -> List[Dict[str, str]]:
|
|
20
|
+
"""Extract Udemy dashboard cards and convert them into records.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
info (Info): Parsed HTML container and counters for the current file.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
List[Dict[str, str]]: List of record dictionaries appended this run.
|
|
27
|
+
"""
|
|
28
|
+
print("udemyscraper scrape")
|
|
29
|
+
soup = info.soup
|
|
30
|
+
append_count = 0
|
|
31
|
+
no_append_count = 0
|
|
32
|
+
"""divの処理"""
|
|
33
|
+
for div_tag in soup.find_all("div", {"class": "enrolled-course-card--container--WJYo9"}):
|
|
34
|
+
# print(f'div_tag={div_tag}')
|
|
35
|
+
a_tag = div_tag.find("a")
|
|
36
|
+
if a_tag is None:
|
|
37
|
+
continue
|
|
38
|
+
url = a_tag.get("href", "#")
|
|
39
|
+
text = a_tag.get_text(strip=True)
|
|
40
|
+
course_id = self.get_course_id_from_url(url)
|
|
41
|
+
|
|
42
|
+
instructors = self.get_instructors(div_tag)
|
|
43
|
+
progress = self.get_progress(div_tag)
|
|
44
|
+
|
|
45
|
+
# Extract course_id from URL parameters
|
|
46
|
+
|
|
47
|
+
result = self.add_list_and_assoc(
|
|
48
|
+
url=url, text=text, course_id=course_id, instructors=instructors, progress=progress
|
|
49
|
+
)
|
|
50
|
+
if result:
|
|
51
|
+
append_count += 1
|
|
52
|
+
else:
|
|
53
|
+
no_append_count += 1
|
|
54
|
+
|
|
55
|
+
info.append_count = append_count
|
|
56
|
+
info.no_append_count = no_append_count
|
|
57
|
+
self.append_count += append_count
|
|
58
|
+
self.no_append_count += no_append_count
|
|
59
|
+
print(f"############### udemyscraper scrape len( self.links_list )={len(self.links_list)}")
|
|
60
|
+
print(f"############### udemyscraper scrape len( self.links_assoc )={len(self.links_assoc)}")
|
|
61
|
+
return self.links_list
|
|
62
|
+
|
|
63
|
+
def get_instructors(self, div_tag) -> List[str]:
|
|
64
|
+
"""Pull the instructor text from a course card.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
div_tag (BeautifulSoup): Card container.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
List[str]: Instructor names (comma-delimited string kept for backward
|
|
71
|
+
compatibility when not parsed further).
|
|
72
|
+
"""
|
|
73
|
+
instructors = ["_0_"]
|
|
74
|
+
child_div = div_tag.find("div", {"data-purpose": "safely-set-inner-html:course-card:visible-instructors"})
|
|
75
|
+
if child_div is not None:
|
|
76
|
+
instructors = child_div.get_text(strip=True)
|
|
77
|
+
|
|
78
|
+
return instructors
|
|
79
|
+
|
|
80
|
+
def get_course_id_from_url(self, url: str) -> str:
|
|
81
|
+
"""Extract ``course_id`` query parameter from a Udemy URL.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
url (str): Anchor ``href`` attribute.
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
str: Course identifier or empty string when absent.
|
|
88
|
+
"""
|
|
89
|
+
if url and url != "#":
|
|
90
|
+
try:
|
|
91
|
+
parsed_url = urlparse(url)
|
|
92
|
+
query_params = parse_qs(parsed_url.query)
|
|
93
|
+
course_id = query_params.get("course_id", [""])[0]
|
|
94
|
+
except Exception:
|
|
95
|
+
course_id = ""
|
|
96
|
+
|
|
97
|
+
return course_id
|
|
98
|
+
|
|
99
|
+
def get_progress(self, div_tag: BeautifulSoup) -> Progress:
|
|
100
|
+
"""Convert the progress meter DOM node into a :class:`Progress`.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
div_tag (BeautifulSoup): Course card container element.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
Progress: Object encapsulating min/max/current values.
|
|
107
|
+
"""
|
|
108
|
+
# meter_div = div_tag.find('div', {'data-purpose': 'meter'})
|
|
109
|
+
meter_div = div_tag.find("div", {"class": "ud-meter meter-module--meter--9-BwT"})
|
|
110
|
+
|
|
111
|
+
meter = ["_0_"]
|
|
112
|
+
meter_str = ""
|
|
113
|
+
valuemin = "0"
|
|
114
|
+
valuemax = "100"
|
|
115
|
+
valuenow = "0"
|
|
116
|
+
meter = f"{valuemin}-{valuemax}-{valuenow}"
|
|
117
|
+
if meter_div is not None:
|
|
118
|
+
# meter = meter_div.get_text(strip=True)
|
|
119
|
+
meter_str = meter_div.get("aria-label", "")
|
|
120
|
+
valuemin = meter_div.get("aria-valuemin", "0")
|
|
121
|
+
valuemax = meter_div.get("aria-valuemax", "100")
|
|
122
|
+
valuenow = meter_div.get("aria-valuenow", "0")
|
|
123
|
+
else:
|
|
124
|
+
print(f"#### meter2={meter}")
|
|
125
|
+
|
|
126
|
+
progress = Progress(meter_str=meter_str, valuemin=valuemin, valuemax=valuemax, valuenow=valuenow)
|
|
127
|
+
return progress
|
|
128
|
+
|
|
129
|
+
def add_list_and_assoc(
|
|
130
|
+
self, url: str, text: str, course_id: str, instructors: List[str], progress: Progress
|
|
131
|
+
) -> bool:
|
|
132
|
+
"""Insert a new record if the ``course_id`` has not been seen.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
url (str): Course URL.
|
|
136
|
+
text (str): Anchor text/label.
|
|
137
|
+
course_id (str): Unique identifier.
|
|
138
|
+
instructors (List[str]): Instructor names.
|
|
139
|
+
progress (Progress): Progress state per card.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
bool: ``True`` when the record was added, else ``False``.
|
|
143
|
+
"""
|
|
144
|
+
result = False
|
|
145
|
+
if course_id not in self.links_assoc.keys():
|
|
146
|
+
# instructors = instructors.split(',')
|
|
147
|
+
# print(f'#### add_list_and_assoc instructors={instructors}')
|
|
148
|
+
record = self.make_record(
|
|
149
|
+
url=url, text=text, course_id=course_id, instructors=instructors, progress=progress
|
|
150
|
+
)
|
|
151
|
+
# record = self.make_record(url, text, course_id)
|
|
152
|
+
# print(f'=1 record1={record}')
|
|
153
|
+
|
|
154
|
+
self.links_assoc[course_id] = record
|
|
155
|
+
# print(f'#### add_list_and_assoc len( self.links_assoc )={ len(self.links_assoc) }')
|
|
156
|
+
self.links_list.append(record)
|
|
157
|
+
result = True
|
|
158
|
+
else:
|
|
159
|
+
pass
|
|
160
|
+
|
|
161
|
+
return result
|
|
162
|
+
|
|
163
|
+
def make_record(
|
|
164
|
+
self, url: str, text: str, course_id: str, instructors: List[str], progress: Progress | Dict
|
|
165
|
+
) -> Dict[str, str]:
|
|
166
|
+
"""Construct the normalized record stored in outputs.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
url (str): Course URL, must be valid.
|
|
170
|
+
text (str): Display name.
|
|
171
|
+
course_id (str): Identifier used as key.
|
|
172
|
+
instructors (List[str]): Instructor strings.
|
|
173
|
+
progress (Progress | Dict): Progress object or dict.
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
Dict[str, str]: Record containing URL/Text/Course_ID/Instructors/Progress.
|
|
177
|
+
|
|
178
|
+
Raises:
|
|
179
|
+
ValueError: If the supplied URL lacks a scheme or structure.
|
|
180
|
+
"""
|
|
181
|
+
if isinstance(progress, dict):
|
|
182
|
+
progress_dict = progress
|
|
183
|
+
else:
|
|
184
|
+
progress_dict = progress.to_dict()
|
|
185
|
+
# print(f'############ make_record instructors={instructors}')
|
|
186
|
+
# print(f'############ make_record progress_yml={progress_dict}')
|
|
187
|
+
"""レコードを作成する"""
|
|
188
|
+
# URI形式のチェック
|
|
189
|
+
parsed = urlparse(url)
|
|
190
|
+
if not parsed.scheme:
|
|
191
|
+
raise ValueError(f"URL '{url}' is not a valid URI: missing scheme")
|
|
192
|
+
if not parsed.netloc and not parsed.path and not parsed.fragment:
|
|
193
|
+
raise ValueError(f"URL '{url}' is not a valid URI: missing authority, path, or fragment")
|
|
194
|
+
# progress_yml = progress.to_yml()
|
|
195
|
+
record = {
|
|
196
|
+
"URL": url,
|
|
197
|
+
"Text": text,
|
|
198
|
+
"Course_ID": course_id,
|
|
199
|
+
"Instructors": instructors,
|
|
200
|
+
"Progress": progress_dict,
|
|
201
|
+
}
|
|
202
|
+
# print(f'0 record0={record}')
|
|
203
|
+
return record
|
|
204
|
+
|
|
205
|
+
def get_link_array(self, extracted_links: List[Dict[str, str]]) -> List[Dict[str, str]]:
|
|
206
|
+
"""Convert associative link data into a list of records.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
extracted_links (List[Dict[str, str]]): Existing course data.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
List[Dict[str, str]]: Cloned records via :meth:`make_record`.
|
|
213
|
+
"""
|
|
214
|
+
print(f"############### get_link_array len(extracted_links)={len(extracted_links)}")
|
|
215
|
+
return [
|
|
216
|
+
self.make_record(
|
|
217
|
+
url=link["URL"],
|
|
218
|
+
text=link["Text"],
|
|
219
|
+
course_id=link["Course_ID"],
|
|
220
|
+
instructors=link["Instructors"],
|
|
221
|
+
progress=link["Progress"],
|
|
222
|
+
)
|
|
223
|
+
for link in extracted_links
|
|
224
|
+
]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .tomlop import Tomlop
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def xmain() -> str:
|
|
5
|
+
print("Hello from yklibpy!")
|
|
6
|
+
return "Hello from yklibpy!"
|
|
7
|
+
|
|
8
|
+
def ymain() -> str:
|
|
9
|
+
print("Y Hello from yklibpy!")
|
|
10
|
+
return "Y Hello from yklibpy!"
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"Tomlop",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
if __name__ == "__main__":
|
|
17
|
+
xmain()
|