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
yklibpy/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# from .htmlparser import htmlparser
|
|
2
|
+
# from .common import common
|
|
3
|
+
# from .tomlop import tomlop
|
|
4
|
+
from .db import db_yaml
|
|
5
|
+
|
|
6
|
+
def dbyaml():
|
|
7
|
+
db_yaml()
|
|
8
|
+
|
|
9
|
+
def xmain() -> str:
|
|
10
|
+
print("11 Hello from yklibpy.xmain!")
|
|
11
|
+
return "12 Hello from yklibpy.xmain!"
|
|
12
|
+
|
|
13
|
+
def ymain() -> str:
|
|
14
|
+
print("21 Y Hello from yklibpy.ymain!")
|
|
15
|
+
return "22 Y Hello from yklibpy.ymain!"
|
|
16
|
+
|
|
17
|
+
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from .env import Env
|
|
2
|
+
from .info import Info
|
|
3
|
+
from .util import Util
|
|
4
|
+
|
|
5
|
+
def xmain() -> str:
|
|
6
|
+
print("Hello from yklibpy!")
|
|
7
|
+
return "Hello from yklibpy!"
|
|
8
|
+
|
|
9
|
+
def ymain() -> str:
|
|
10
|
+
print("Y Hello from yklibpy!")
|
|
11
|
+
return "Y Hello from yklibpy!"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
if __name__ == "__main__":
|
|
15
|
+
xmain()
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import yaml
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
# PyYAML が付ける / あるいは YAML 内に書かれている可能性のあるタグ表現
|
|
10
|
+
DYNAMIC_INLINE_TABLE_TAGS = {
|
|
11
|
+
"tag:yaml.org,2002:python/object/new:toml.decoder.DynamicInlineTableDict",
|
|
12
|
+
"!!python/object/new:toml.decoder.DynamicInlineTableDict", # 念のため
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TagStrippingSafeLoader(yaml.SafeLoader):
|
|
17
|
+
"""
|
|
18
|
+
SafeLoader をベースにしつつ、特定の python/object/new タグだけ
|
|
19
|
+
普通の dict に落とすための Loader。
|
|
20
|
+
"""
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _dynamic_inline_table_dict_constructor(loader: yaml.SafeLoader, node: yaml.Node):
|
|
25
|
+
# node が mapping の想定
|
|
26
|
+
mapping = loader.construct_mapping(node, deep=True)
|
|
27
|
+
# toml の DynamicInlineTableDict は dictitems キー配下に実体が入っていることが多い
|
|
28
|
+
if isinstance(mapping, dict) and "dictitems" in mapping and isinstance(mapping["dictitems"], dict):
|
|
29
|
+
return mapping["dictitems"]
|
|
30
|
+
return mapping
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _register_constructors():
|
|
34
|
+
# 代表的なタグ(tag:...形式)を登録
|
|
35
|
+
TagStrippingSafeLoader.add_constructor(
|
|
36
|
+
"tag:yaml.org,2002:python/object/new:toml.decoder.DynamicInlineTableDict",
|
|
37
|
+
_dynamic_inline_table_dict_constructor,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# YAML 内で !!python/object/new:... と書かれていた場合に備えて multi_constructor も登録
|
|
41
|
+
def _multi_python_object_new(loader: yaml.SafeLoader, tag_suffix: str, node: yaml.Node):
|
|
42
|
+
# tag_suffix は "toml.decoder.DynamicInlineTableDict" のような文字列になる
|
|
43
|
+
full = f"tag:yaml.org,2002:python/object/new:{tag_suffix}"
|
|
44
|
+
if full == "tag:yaml.org,2002:python/object/new:toml.decoder.DynamicInlineTableDict":
|
|
45
|
+
return _dynamic_inline_table_dict_constructor(loader, node)
|
|
46
|
+
# それ以外の python/object/new は安全のため許可しない(明示的に失敗させる)
|
|
47
|
+
raise yaml.constructor.ConstructorError(
|
|
48
|
+
None, None,
|
|
49
|
+
f"Unsupported python/object/new tag: {full} (refuse to construct). "
|
|
50
|
+
f"Please strip/convert this node explicitly.",
|
|
51
|
+
node.start_mark,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
TagStrippingSafeLoader.add_multi_constructor(
|
|
55
|
+
"tag:yaml.org,2002:python/object/new:",
|
|
56
|
+
_multi_python_object_new,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def strip_tags_and_dump(input_path: Path, output_path: Path):
|
|
61
|
+
text = input_path.read_text(encoding="utf-8")
|
|
62
|
+
|
|
63
|
+
data = yaml.load(text, Loader=TagStrippingSafeLoader)
|
|
64
|
+
|
|
65
|
+
# タグ無しで人間が読みやすい YAML を出力
|
|
66
|
+
dumped = yaml.safe_dump(
|
|
67
|
+
data,
|
|
68
|
+
allow_unicode=True,
|
|
69
|
+
sort_keys=False,
|
|
70
|
+
default_flow_style=False,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
output_path.write_text(dumped, encoding="utf-8")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def main():
|
|
77
|
+
_register_constructors()
|
|
78
|
+
|
|
79
|
+
parser = argparse.ArgumentParser(
|
|
80
|
+
description="Convert YAML containing python/object/new tags into plain tag-free YAML."
|
|
81
|
+
)
|
|
82
|
+
parser.add_argument("input", type=Path, help="Input YAML path (e.g. a.yaml)")
|
|
83
|
+
parser.add_argument(
|
|
84
|
+
"-o", "--output",
|
|
85
|
+
type=Path,
|
|
86
|
+
default=None,
|
|
87
|
+
help="Output YAML path (default: <input>.stripped.yaml)",
|
|
88
|
+
)
|
|
89
|
+
args = parser.parse_args()
|
|
90
|
+
|
|
91
|
+
in_path: Path = args.input
|
|
92
|
+
if args.output is None:
|
|
93
|
+
out_path = in_path.with_suffix(in_path.suffix + ".stripped.yaml")
|
|
94
|
+
else:
|
|
95
|
+
out_path = args.output
|
|
96
|
+
|
|
97
|
+
strip_tags_and_dump(in_path, out_path)
|
|
98
|
+
print(f"written: {out_path}")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
if __name__ == "__main__":
|
|
102
|
+
main()
|
yklibpy/common/env.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import List, Optional
|
|
3
|
+
|
|
4
|
+
import yaml
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Env:
|
|
8
|
+
def __init__(self, config_path: Path = None):
|
|
9
|
+
"""Load configuration and initialize base path/mode settings.
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
config_path (Path | None): YAML containing ``base_path`` and pattern
|
|
13
|
+
associations. When ``None`` the environment starts empty.
|
|
14
|
+
|
|
15
|
+
Returns:
|
|
16
|
+
None
|
|
17
|
+
"""
|
|
18
|
+
self.base_path = None
|
|
19
|
+
self.pattern = None
|
|
20
|
+
self.config = {}
|
|
21
|
+
self.assoc = {}
|
|
22
|
+
# print(f"config_path={config_path}")
|
|
23
|
+
if config_path is not None:
|
|
24
|
+
with open(config_path, "r", encoding="utf-8") as f:
|
|
25
|
+
self.assoc = yaml.load(f, Loader=yaml.FullLoader)
|
|
26
|
+
# print(list(self.assoc.keys()))
|
|
27
|
+
# list = self.assoc.keys()
|
|
28
|
+
# for key in list:
|
|
29
|
+
# print(f"key={key}")
|
|
30
|
+
|
|
31
|
+
base_path_array = self.assoc["base_path"]
|
|
32
|
+
self.base_path = self.make_path(base_path_array)
|
|
33
|
+
|
|
34
|
+
def make_path(self, path_array: list[str]) -> Path | None:
|
|
35
|
+
"""Convert a sequence of path components into a concrete path.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
path_array (list[str]): Ordered segments such as
|
|
39
|
+
``['C:/data', 'courses']``.
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
Path | None: Composed path or ``None`` when no components exist.
|
|
43
|
+
"""
|
|
44
|
+
base_path = None
|
|
45
|
+
if path_array is not None:
|
|
46
|
+
top_dir = path_array.pop(0)
|
|
47
|
+
top_path = Path(top_dir)
|
|
48
|
+
base_path = top_path / Path(*path_array)
|
|
49
|
+
|
|
50
|
+
return base_path
|
|
51
|
+
|
|
52
|
+
def mode(self):
|
|
53
|
+
"""Return the scraper mode stored in the active pattern.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
str: Mode string, defaulting to ``"H3"`` when unspecified.
|
|
57
|
+
"""
|
|
58
|
+
mode = self.config["mode"]
|
|
59
|
+
if mode is None:
|
|
60
|
+
mode = "H3"
|
|
61
|
+
return mode
|
|
62
|
+
|
|
63
|
+
def set_base_path(self, base_path: Path):
|
|
64
|
+
"""Persist an externally provided root directory.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
base_path (Path): Directory serving as the root for pattern paths.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
None
|
|
71
|
+
"""
|
|
72
|
+
self.base_path = base_path
|
|
73
|
+
|
|
74
|
+
def set_pattern(self, pattern: str):
|
|
75
|
+
"""Load the configuration block associated with ``pattern``.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
pattern (str): Key in ``assoc`` (e.g., ``'Udemy-2-file'``).
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
dict | None: Selected configuration or ``None`` when unknown.
|
|
82
|
+
"""
|
|
83
|
+
self.pattern = pattern
|
|
84
|
+
if pattern not in self.assoc:
|
|
85
|
+
return None
|
|
86
|
+
self.config = self.assoc[pattern]
|
|
87
|
+
return self.config
|
|
88
|
+
|
|
89
|
+
def get_files(self) -> List[Path]:
|
|
90
|
+
"""Resolve the files or directory contents defined by the pattern.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
List[Path]: Concrete file paths ready for scraping.
|
|
94
|
+
"""
|
|
95
|
+
if len(self.config) == 0:
|
|
96
|
+
return []
|
|
97
|
+
else:
|
|
98
|
+
dir_path = self.base_path / Path(*self.config["dir"])
|
|
99
|
+
|
|
100
|
+
if self.config["kind"] == "file":
|
|
101
|
+
# 指定されたファイルのみを返す
|
|
102
|
+
files = self.config.get("files", [])
|
|
103
|
+
return [dir_path / file for file in files]
|
|
104
|
+
else:
|
|
105
|
+
# 指定ディレクトリの直下に存在するファイルの一覧を返す
|
|
106
|
+
if not dir_path.exists() or not dir_path.is_dir():
|
|
107
|
+
return []
|
|
108
|
+
files = [f for f in dir_path.iterdir() if f.is_file()]
|
|
109
|
+
return sorted(files)
|
yklibpy/common/info.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
from bs4 import BeautifulSoup
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Info:
|
|
7
|
+
def __init__(self, file_path: Path, name: str, soup: BeautifulSoup, append_count: int, no_append_count: int):
|
|
8
|
+
"""Bundle parsed HTML and bookkeeping counters.
|
|
9
|
+
|
|
10
|
+
Args:
|
|
11
|
+
file_path (Path): Source HTML path.
|
|
12
|
+
name (str): Friendly identifier, typically the filename.
|
|
13
|
+
soup (BeautifulSoup): Parsed DOM tree to inspect.
|
|
14
|
+
append_count (int): Number of records added so far.
|
|
15
|
+
no_append_count (int): Number of skipped records.
|
|
16
|
+
|
|
17
|
+
Returns:
|
|
18
|
+
None
|
|
19
|
+
"""
|
|
20
|
+
self.file_path = file_path
|
|
21
|
+
self.name = name
|
|
22
|
+
self.soup = soup
|
|
23
|
+
self.append_count = append_count
|
|
24
|
+
self.no_append_count = no_append_count
|
yklibpy/common/util.py
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
from io import StringIO
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Optional, Sequence, List, Iterable, Literal
|
|
5
|
+
from urllib.parse import urlparse
|
|
6
|
+
|
|
7
|
+
import yaml
|
|
8
|
+
import chardet
|
|
9
|
+
import locale
|
|
10
|
+
from bs4 import Tag, NavigableString
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
TargetType = Literal["file", "dir", "both"]
|
|
14
|
+
|
|
15
|
+
class Util:
|
|
16
|
+
class UniqueList:
|
|
17
|
+
def __init__(self):
|
|
18
|
+
self._set = set()
|
|
19
|
+
self._list = []
|
|
20
|
+
|
|
21
|
+
def append(self, value):
|
|
22
|
+
if value not in self._set:
|
|
23
|
+
self._set.add(value)
|
|
24
|
+
self._list.append(value)
|
|
25
|
+
|
|
26
|
+
def __iter__(self):
|
|
27
|
+
return iter(self._list)
|
|
28
|
+
|
|
29
|
+
def __repr__(self):
|
|
30
|
+
return repr(self._list)
|
|
31
|
+
|
|
32
|
+
class Result:
|
|
33
|
+
def __init__(self, success: bool, url: str, reason: str, parsed: urlparse):
|
|
34
|
+
self.success = success
|
|
35
|
+
self.url = url
|
|
36
|
+
self.reason = reason
|
|
37
|
+
self.parsed = parsed
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def get_location_string() -> str:
|
|
41
|
+
"""現在の位置を文字列で返す"""
|
|
42
|
+
frame = inspect.currentframe()
|
|
43
|
+
if frame and frame.f_back:
|
|
44
|
+
caller = frame.f_back
|
|
45
|
+
filename = Path(caller.f_filename).name
|
|
46
|
+
lineno = caller.f_lineno
|
|
47
|
+
function = caller.f_code.co_name
|
|
48
|
+
return f"{filename}:{lineno} in {function}"
|
|
49
|
+
return "unknown"
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def xyz():
|
|
53
|
+
print("xyz")
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def find_paths(
|
|
57
|
+
cls,
|
|
58
|
+
base_dir: Path,
|
|
59
|
+
pattern: str,
|
|
60
|
+
target_type: TargetType = "both",
|
|
61
|
+
) -> list[Path]:
|
|
62
|
+
"""
|
|
63
|
+
指定ディレクトリ配下を再帰的に探索し、パターンに一致するパスを取得する
|
|
64
|
+
|
|
65
|
+
:param base_dir: 探索開始ディレクトリ (Path)
|
|
66
|
+
:param pattern: globパターン (例: "*.py", "data_*")
|
|
67
|
+
:param target_type: "file" | "dir" | "both"
|
|
68
|
+
:return: Path のリスト
|
|
69
|
+
"""
|
|
70
|
+
if not base_dir.is_dir():
|
|
71
|
+
raise ValueError(f"{base_dir} はディレクトリではありません")
|
|
72
|
+
|
|
73
|
+
results: list[Path] = []
|
|
74
|
+
|
|
75
|
+
print(f'base_dir={base_dir}')
|
|
76
|
+
# print(f'pattern={pattern}')
|
|
77
|
+
for path in base_dir.rglob(pattern):
|
|
78
|
+
# print(f'path={path}')
|
|
79
|
+
if target_type == "file" and path.is_file():
|
|
80
|
+
results.append(path)
|
|
81
|
+
elif target_type == "dir" and path.is_dir():
|
|
82
|
+
results.append(path)
|
|
83
|
+
elif target_type == "both":
|
|
84
|
+
results.append(path)
|
|
85
|
+
|
|
86
|
+
print(f'results={results}')
|
|
87
|
+
return results
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
def list_files(cls, name, parts, suffix):
|
|
91
|
+
list = [f'{name}-{part}{suffix}'for part in parts]
|
|
92
|
+
return list
|
|
93
|
+
|
|
94
|
+
@classmethod
|
|
95
|
+
def isValidUrls(cls, urls: [str]) -> str | None:
|
|
96
|
+
result_array = []
|
|
97
|
+
for url in urls:
|
|
98
|
+
if url == "" or url is None:
|
|
99
|
+
result = cls.Result(False, url , "URL is empty", None)
|
|
100
|
+
result_array.append(result)
|
|
101
|
+
continue
|
|
102
|
+
|
|
103
|
+
parsed = urlparse(url)
|
|
104
|
+
if not parsed.scheme:
|
|
105
|
+
result = cls.Result(False, url , "URL scheme is invalid", parsed)
|
|
106
|
+
result_array.append(result)
|
|
107
|
+
continue
|
|
108
|
+
|
|
109
|
+
if not parsed.netloc and not parsed.path and not parsed.fragment:
|
|
110
|
+
result = cls.Result(False, url , "URL is not a valid URI: missing authority, path, or fragment", parsed)
|
|
111
|
+
result_array.append(result)
|
|
112
|
+
continue
|
|
113
|
+
|
|
114
|
+
result = cls.Result(True, url , "URL is valid", parsed)
|
|
115
|
+
result_array.append(result)
|
|
116
|
+
return result_array
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def extract_cid(cls, text: str) -> str | None:
|
|
120
|
+
m = re.search(r'cid=([^/?&]+)', text)
|
|
121
|
+
return m.group(1) if m else None
|
|
122
|
+
|
|
123
|
+
@classmethod
|
|
124
|
+
def extract_base(cls, base: str, text: str) -> str | None:
|
|
125
|
+
re_text = f'{base}=([^/?&]+)'
|
|
126
|
+
regexp = re.compile(re_text)
|
|
127
|
+
m = regexp.search(text)
|
|
128
|
+
return m.group(1) if m else None
|
|
129
|
+
|
|
130
|
+
@classmethod
|
|
131
|
+
def flatten_gen(cls, lst):
|
|
132
|
+
for item in lst:
|
|
133
|
+
if isinstance(item, list):
|
|
134
|
+
yield from Util.flatten_gen(item)
|
|
135
|
+
else:
|
|
136
|
+
yield item
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@classmethod
|
|
140
|
+
def ensure_file_path(cls, path: Path) -> Path:
|
|
141
|
+
if path is None:
|
|
142
|
+
return None
|
|
143
|
+
if not path.exists():
|
|
144
|
+
parent_path = path.parent
|
|
145
|
+
if not parent_path.exists():
|
|
146
|
+
parent_path.mkdir(parents=True, exist_ok=True)
|
|
147
|
+
path.touch()
|
|
148
|
+
return path
|
|
149
|
+
|
|
150
|
+
@classmethod
|
|
151
|
+
def ensure_dir_path(cls, path: Path) -> Path:
|
|
152
|
+
if path is None:
|
|
153
|
+
return None
|
|
154
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
155
|
+
return path
|
|
156
|
+
|
|
157
|
+
@classmethod
|
|
158
|
+
def flatten(cls, items):
|
|
159
|
+
"""Flatten arbitrarily nested iterables into a single list.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
items (Iterable): Possibly nested lists/tuples of values.
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
list: Flattened sequence preserving order.
|
|
166
|
+
"""
|
|
167
|
+
flat_list = []
|
|
168
|
+
for item in items:
|
|
169
|
+
if isinstance(item, list):
|
|
170
|
+
flat_list.extend(cls.flatten(item))
|
|
171
|
+
else:
|
|
172
|
+
flat_list.append(item)
|
|
173
|
+
|
|
174
|
+
return flat_list
|
|
175
|
+
|
|
176
|
+
@classmethod
|
|
177
|
+
def detect_encoding(cls, input_path: Path) -> str:
|
|
178
|
+
if input_path is not None:
|
|
179
|
+
with open(input_path, "rb") as f:
|
|
180
|
+
raw = f.read()
|
|
181
|
+
encoding = chardet.detect(raw)["encoding"]
|
|
182
|
+
return encoding
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
@classmethod
|
|
186
|
+
def get_default_encoding(cls) -> str:
|
|
187
|
+
enc = locale.getpreferredencoding(False)
|
|
188
|
+
return enc
|
|
189
|
+
|
|
190
|
+
@classmethod
|
|
191
|
+
def get_common_parents(cls, element1: Tag, element2: Tag) -> List[Tag]:
|
|
192
|
+
"""2つのBeautifulSoup要素の共通する親要素をすべて取得する。
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
element1 (Tag): 最初の要素
|
|
196
|
+
element2 (Tag): 2番目の要素
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
List[Tag]: 共通する親要素のリスト(ルートから近い順、つまり最も近い共通親が最後)
|
|
200
|
+
|
|
201
|
+
Examples:
|
|
202
|
+
>>> from bs4 import BeautifulSoup
|
|
203
|
+
>>> soup = BeautifulSoup('<div><p><span>text1</span></p><p><span>text2</span></p></div>', 'html.parser')
|
|
204
|
+
>>> span1 = soup.find_all('span')[0]
|
|
205
|
+
>>> span2 = soup.find_all('span')[1]
|
|
206
|
+
>>> common_parents = Util.get_common_parents(span1, span2)
|
|
207
|
+
>>> # [<div>...</div>, <html>...</html>, <body>...</body>] などが返される
|
|
208
|
+
"""
|
|
209
|
+
def get_all_parents(element: Tag) -> List[Tag]:
|
|
210
|
+
"""要素のすべての親要素をルートまで取得する"""
|
|
211
|
+
parents = []
|
|
212
|
+
current = element.parent
|
|
213
|
+
while current is not None and hasattr(current, 'name'):
|
|
214
|
+
# NavigableStringやNoneを除外し、Tagのみを対象とする
|
|
215
|
+
if isinstance(current, Tag):
|
|
216
|
+
parents.append(current)
|
|
217
|
+
current = current.parent
|
|
218
|
+
return parents
|
|
219
|
+
|
|
220
|
+
parents1 = get_all_parents(element1)
|
|
221
|
+
parents2 = get_all_parents(element2)
|
|
222
|
+
|
|
223
|
+
# 共通する親要素を見つける(順序を保持)
|
|
224
|
+
common_parents = []
|
|
225
|
+
# ルートから近い順に比較するため、逆順にする
|
|
226
|
+
parents1_reversed = list(reversed(parents1))
|
|
227
|
+
parents2_reversed = list(reversed(parents2))
|
|
228
|
+
|
|
229
|
+
# 両方のリストをセットに変換して高速化
|
|
230
|
+
parents2_set = set(id(p) for p in parents2_reversed)
|
|
231
|
+
|
|
232
|
+
# 共通する親要素を順序を保持して取得
|
|
233
|
+
for parent in parents1_reversed:
|
|
234
|
+
if id(parent) in parents2_set:
|
|
235
|
+
common_parents.append(parent)
|
|
236
|
+
|
|
237
|
+
return common_parents
|
|
238
|
+
|
|
239
|
+
@classmethod
|
|
240
|
+
def load_yaml(cls, input_path: Path) -> dict:
|
|
241
|
+
"""Load a YAML file and return it as a dictionary.
|
|
242
|
+
|
|
243
|
+
Args:
|
|
244
|
+
input_path (Path): Path to the YAML file.
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
dict: Parsed YAML content.
|
|
248
|
+
"""
|
|
249
|
+
data = {}
|
|
250
|
+
with open(input_path, "r", encoding="utf-8") as f:
|
|
251
|
+
data = yaml.load(f, Loader=yaml.FullLoader)
|
|
252
|
+
if data is None:
|
|
253
|
+
data = {}
|
|
254
|
+
return data
|
|
255
|
+
|
|
256
|
+
@classmethod
|
|
257
|
+
def save_yaml(cls, assoc: dict, output_path: Optional[Path] = None) -> str:
|
|
258
|
+
"""Serialize a dictionary to YAML and optionally save it to disk.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
assoc (dict): Data to dump.
|
|
262
|
+
output_path (Path | None): Destination path. When ``None`` the YAML
|
|
263
|
+
string is merely returned.
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
str: YAML representation of ``assoc``.
|
|
267
|
+
"""
|
|
268
|
+
yaml_str = yaml.dump(assoc, default_flow_style=False, allow_unicode=True, sort_keys=False)
|
|
269
|
+
|
|
270
|
+
if output_path is not None:
|
|
271
|
+
with open(output_path, "w", encoding="utf-8") as f:
|
|
272
|
+
f.write(yaml_str)
|
|
273
|
+
|
|
274
|
+
return yaml_str
|
|
275
|
+
|
|
276
|
+
@classmethod
|
|
277
|
+
def load_tsv(cls, input_path: Path, fieldnames: Optional[Sequence[str]] = None) -> list[dict]:
|
|
278
|
+
"""Read a TSV file and convert rows into dictionaries.
|
|
279
|
+
|
|
280
|
+
Args:
|
|
281
|
+
input_path (Path): TSV file path.
|
|
282
|
+
fieldnames (Sequence[str] | None): Explicit headers. When ``None`` the
|
|
283
|
+
first row becomes the header.
|
|
284
|
+
|
|
285
|
+
Returns:
|
|
286
|
+
list[dict]: Each row keyed by the header columns.
|
|
287
|
+
|
|
288
|
+
Raises:
|
|
289
|
+
ValueError: If no headers can be determined.
|
|
290
|
+
"""
|
|
291
|
+
records = []
|
|
292
|
+
with open(input_path, "r", encoding="utf-8", newline="") as f:
|
|
293
|
+
reader = csv.reader(f, delimiter="\t")
|
|
294
|
+
headers = list(fieldnames) if fieldnames is not None else None
|
|
295
|
+
|
|
296
|
+
for row in reader:
|
|
297
|
+
if headers is None:
|
|
298
|
+
headers = row
|
|
299
|
+
continue
|
|
300
|
+
record = {key: value for key, value in zip(headers, row)}
|
|
301
|
+
records.append(record)
|
|
302
|
+
|
|
303
|
+
if headers is None:
|
|
304
|
+
raise ValueError("ヘッダー行が存在しません。fieldnamesを指定してください。")
|
|
305
|
+
|
|
306
|
+
return records
|
|
307
|
+
|
|
308
|
+
@classmethod
|
|
309
|
+
def output_tsv(
|
|
310
|
+
cls, records: Sequence[dict], output_path: Optional[Path] = None, fieldnames: Optional[Sequence[str]] = None
|
|
311
|
+
) -> str:
|
|
312
|
+
"""Write record dictionaries to TSV format.
|
|
313
|
+
|
|
314
|
+
Args:
|
|
315
|
+
records (Sequence[dict]): Rows to emit.
|
|
316
|
+
output_path (Path | None): Optional destination file.
|
|
317
|
+
fieldnames (Sequence[str] | None): Header order override; defaults to
|
|
318
|
+
keys of the first record.
|
|
319
|
+
|
|
320
|
+
Returns:
|
|
321
|
+
str: TSV string containing the headers and rows.
|
|
322
|
+
|
|
323
|
+
Raises:
|
|
324
|
+
ValueError: If neither records nor ``fieldnames`` are provided.
|
|
325
|
+
"""
|
|
326
|
+
if not records and fieldnames is None:
|
|
327
|
+
raise ValueError("fieldnamesを指定するか、recordsに1件以上のデータを含めてください。")
|
|
328
|
+
|
|
329
|
+
if fieldnames is None:
|
|
330
|
+
headers = []
|
|
331
|
+
else:
|
|
332
|
+
headers = fieldnames
|
|
333
|
+
|
|
334
|
+
buffer = StringIO()
|
|
335
|
+
writer = csv.writer(buffer, delimiter="\t", lineterminator="\n")
|
|
336
|
+
writer.writerow(headers)
|
|
337
|
+
for record in records:
|
|
338
|
+
# print(record)
|
|
339
|
+
# print(headers)
|
|
340
|
+
row = [record.get(header, "") for header in headers]
|
|
341
|
+
writer.writerow(row)
|
|
342
|
+
|
|
343
|
+
tsv_str = buffer.getvalue()
|
|
344
|
+
|
|
345
|
+
if output_path is not None:
|
|
346
|
+
with open(output_path, "w", encoding="utf-8", newline="") as f:
|
|
347
|
+
f.write(tsv_str)
|
|
348
|
+
|
|
349
|
+
return tsv_str
|
|
350
|
+
|
|
351
|
+
def test_yaml(self, input_file:str, input_file_2:str, output_file:str):
|
|
352
|
+
"""Developer helper for merging Udemy YAML progress data.
|
|
353
|
+
|
|
354
|
+
Returns:
|
|
355
|
+
None
|
|
356
|
+
"""
|
|
357
|
+
input_path = Path(input_file)
|
|
358
|
+
input_path_2 = Path(input_file_2)
|
|
359
|
+
output_path = Path(output_file)
|
|
360
|
+
dict = Util.load_yaml(input_path)
|
|
361
|
+
# print(dict)
|
|
362
|
+
|
|
363
|
+
dict_2 = Util.load_yaml(input_path_2)
|
|
364
|
+
#
|
|
365
|
+
output_tsv_path = input_path_2.with_suffix(".tsv")
|
|
366
|
+
output_tsv_path_2 = output_path.with_suffix(".tsv")
|
|
367
|
+
# keys = dict.keys()
|
|
368
|
+
values = dict.values()
|
|
369
|
+
# print(values)
|
|
370
|
+
keys = list(values)[0].keys()
|
|
371
|
+
Util.output_tsv(values, output_tsv_path, keys)
|
|
372
|
+
# exit()
|
|
373
|
+
values_2 = dict_2.values()
|
|
374
|
+
keys_2 = list(values_2)[0].keys()
|
|
375
|
+
Util.output_tsv(values_2, output_tsv_path_2, keys_2)
|
|
376
|
+
|
|
377
|
+
for key_2, value_2 in dict_2.items():
|
|
378
|
+
value_2["Time"] = "0時間"
|
|
379
|
+
if key_2 in dict.keys():
|
|
380
|
+
value = dict[key_2]
|
|
381
|
+
if "Time" in value.keys():
|
|
382
|
+
value_2["Time"] = value["Time"]
|
|
383
|
+
else:
|
|
384
|
+
value_2["Time"] = "0時間"
|
|
385
|
+
|
|
386
|
+
Util.save_yaml(dict_2, output_path)
|
|
387
|
+
|
|
388
|
+
def test_tsv(self, input_file:str, input_file_2:str, output_file:str):
|
|
389
|
+
"""Developer helper for merging Udemy TSV progress data.
|
|
390
|
+
|
|
391
|
+
Returns:
|
|
392
|
+
None
|
|
393
|
+
"""
|
|
394
|
+
input_path = Path(input_file)
|
|
395
|
+
dict = Util.load_yaml(input_path)
|
|
396
|
+
|
|
397
|
+
# input_path = Path('output_2.tsv')
|
|
398
|
+
input_path_2 = Path(input_file_2)
|
|
399
|
+
output_path = Path(output_file)
|
|
400
|
+
dict = Util.load_tsv(input_path)
|
|
401
|
+
dict_2 = Util.load_tsv(input_path_2)
|
|
402
|
+
for record_2 in dict_2:
|
|
403
|
+
record_2["Time"] = "0時間"
|
|
404
|
+
if "Course_ID" in dict:
|
|
405
|
+
record = dict[record_2["Course_ID"]]
|
|
406
|
+
if "Time" in record.keys():
|
|
407
|
+
record_2["Time"] = record["Time"]
|
|
408
|
+
else:
|
|
409
|
+
record_2["Time"] = "0時間"
|
|
410
|
+
Util.output_tsv(dict_2, output_path)
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
if __name__ == "__main__":
|
|
414
|
+
# test_util = Util()
|
|
415
|
+
# test_util.test_yaml(input_file="output_udemy_2.yaml", input_file_2="output_udemy_4.yaml", output_file="output_udemy_5.yaml")
|
|
416
|
+
# test_util.test_tsv(input_file="output_udemy_4.tsv", input_file_2="output_udemy_5.tsv", output_file="output_udemy_6.tsv")
|
|
417
|
+
str = "https://www.dmm.co.jp/dc/doujin/-/detail/=/cid=d_573976/?dmmref=Basket&i3_ref=recommend&i3_ord=1"
|
|
418
|
+
ret = Util.extract_cid(str)
|
|
419
|
+
print(ret)
|