webscout 8.2.6__py3-none-any.whl → 8.2.8__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.

Potentially problematic release.


This version of webscout might be problematic. Click here for more details.

Files changed (150) hide show
  1. webscout/AIauto.py +1 -1
  2. webscout/AIutel.py +298 -239
  3. webscout/Extra/Act.md +309 -0
  4. webscout/Extra/GitToolkit/gitapi/README.md +110 -0
  5. webscout/Extra/YTToolkit/README.md +375 -0
  6. webscout/Extra/YTToolkit/ytapi/README.md +44 -0
  7. webscout/Extra/YTToolkit/ytapi/extras.py +92 -19
  8. webscout/Extra/autocoder/autocoder.py +309 -114
  9. webscout/Extra/autocoder/autocoder_utiles.py +15 -15
  10. webscout/Extra/gguf.md +430 -0
  11. webscout/Extra/tempmail/README.md +488 -0
  12. webscout/Extra/weather.md +281 -0
  13. webscout/Litlogger/Readme.md +175 -0
  14. webscout/Provider/AISEARCH/DeepFind.py +41 -37
  15. webscout/Provider/AISEARCH/README.md +279 -0
  16. webscout/Provider/AISEARCH/__init__.py +0 -1
  17. webscout/Provider/AISEARCH/genspark_search.py +228 -86
  18. webscout/Provider/AISEARCH/hika_search.py +11 -11
  19. webscout/Provider/AISEARCH/scira_search.py +324 -322
  20. webscout/Provider/AllenAI.py +7 -14
  21. webscout/Provider/Blackboxai.py +518 -74
  22. webscout/Provider/Cloudflare.py +0 -1
  23. webscout/Provider/Deepinfra.py +23 -21
  24. webscout/Provider/Flowith.py +217 -0
  25. webscout/Provider/FreeGemini.py +250 -0
  26. webscout/Provider/GizAI.py +15 -5
  27. webscout/Provider/Glider.py +11 -8
  28. webscout/Provider/HeckAI.py +80 -52
  29. webscout/Provider/Koboldai.py +7 -4
  30. webscout/Provider/LambdaChat.py +2 -2
  31. webscout/Provider/Marcus.py +10 -18
  32. webscout/Provider/OPENAI/BLACKBOXAI.py +735 -0
  33. webscout/Provider/OPENAI/Cloudflare.py +378 -0
  34. webscout/Provider/OPENAI/FreeGemini.py +282 -0
  35. webscout/Provider/OPENAI/NEMOTRON.py +244 -0
  36. webscout/Provider/OPENAI/README.md +1253 -0
  37. webscout/Provider/OPENAI/__init__.py +8 -0
  38. webscout/Provider/OPENAI/ai4chat.py +293 -286
  39. webscout/Provider/OPENAI/api.py +810 -0
  40. webscout/Provider/OPENAI/base.py +217 -14
  41. webscout/Provider/OPENAI/c4ai.py +373 -367
  42. webscout/Provider/OPENAI/chatgpt.py +7 -0
  43. webscout/Provider/OPENAI/chatgptclone.py +7 -0
  44. webscout/Provider/OPENAI/chatsandbox.py +172 -0
  45. webscout/Provider/OPENAI/deepinfra.py +30 -20
  46. webscout/Provider/OPENAI/e2b.py +6 -0
  47. webscout/Provider/OPENAI/exaai.py +7 -0
  48. webscout/Provider/OPENAI/exachat.py +6 -0
  49. webscout/Provider/OPENAI/flowith.py +162 -0
  50. webscout/Provider/OPENAI/freeaichat.py +359 -352
  51. webscout/Provider/OPENAI/glider.py +323 -316
  52. webscout/Provider/OPENAI/groq.py +361 -354
  53. webscout/Provider/OPENAI/heckai.py +30 -64
  54. webscout/Provider/OPENAI/llmchatco.py +8 -0
  55. webscout/Provider/OPENAI/mcpcore.py +7 -0
  56. webscout/Provider/OPENAI/multichat.py +8 -0
  57. webscout/Provider/OPENAI/netwrck.py +356 -350
  58. webscout/Provider/OPENAI/opkfc.py +8 -0
  59. webscout/Provider/OPENAI/scirachat.py +471 -462
  60. webscout/Provider/OPENAI/sonus.py +9 -0
  61. webscout/Provider/OPENAI/standardinput.py +9 -1
  62. webscout/Provider/OPENAI/textpollinations.py +339 -329
  63. webscout/Provider/OPENAI/toolbaz.py +7 -0
  64. webscout/Provider/OPENAI/typefully.py +355 -0
  65. webscout/Provider/OPENAI/typegpt.py +358 -346
  66. webscout/Provider/OPENAI/uncovrAI.py +7 -0
  67. webscout/Provider/OPENAI/utils.py +103 -7
  68. webscout/Provider/OPENAI/venice.py +12 -0
  69. webscout/Provider/OPENAI/wisecat.py +19 -19
  70. webscout/Provider/OPENAI/writecream.py +7 -0
  71. webscout/Provider/OPENAI/x0gpt.py +7 -0
  72. webscout/Provider/OPENAI/yep.py +50 -21
  73. webscout/Provider/OpenGPT.py +1 -1
  74. webscout/Provider/TTI/AiForce/README.md +159 -0
  75. webscout/Provider/TTI/FreeAIPlayground/README.md +99 -0
  76. webscout/Provider/TTI/ImgSys/README.md +174 -0
  77. webscout/Provider/TTI/MagicStudio/README.md +101 -0
  78. webscout/Provider/TTI/Nexra/README.md +155 -0
  79. webscout/Provider/TTI/PollinationsAI/README.md +146 -0
  80. webscout/Provider/TTI/README.md +128 -0
  81. webscout/Provider/TTI/aiarta/README.md +134 -0
  82. webscout/Provider/TTI/artbit/README.md +100 -0
  83. webscout/Provider/TTI/fastflux/README.md +129 -0
  84. webscout/Provider/TTI/huggingface/README.md +114 -0
  85. webscout/Provider/TTI/piclumen/README.md +161 -0
  86. webscout/Provider/TTI/pixelmuse/README.md +79 -0
  87. webscout/Provider/TTI/talkai/README.md +139 -0
  88. webscout/Provider/TTS/README.md +192 -0
  89. webscout/Provider/TTS/__init__.py +2 -1
  90. webscout/Provider/TTS/speechma.py +500 -100
  91. webscout/Provider/TTS/sthir.py +94 -0
  92. webscout/Provider/TeachAnything.py +3 -7
  93. webscout/Provider/TextPollinationsAI.py +4 -2
  94. webscout/Provider/{aimathgpt.py → UNFINISHED/ChatHub.py} +88 -68
  95. webscout/Provider/UNFINISHED/liner_api_request.py +263 -0
  96. webscout/Provider/UNFINISHED/oivscode.py +351 -0
  97. webscout/Provider/UNFINISHED/test_lmarena.py +119 -0
  98. webscout/Provider/Writecream.py +11 -2
  99. webscout/Provider/__init__.py +8 -14
  100. webscout/Provider/ai4chat.py +4 -58
  101. webscout/Provider/asksteve.py +17 -9
  102. webscout/Provider/cerebras.py +3 -1
  103. webscout/Provider/koala.py +170 -268
  104. webscout/Provider/llmchat.py +3 -0
  105. webscout/Provider/lmarena.py +198 -0
  106. webscout/Provider/meta.py +7 -4
  107. webscout/Provider/samurai.py +223 -0
  108. webscout/Provider/scira_chat.py +4 -2
  109. webscout/Provider/typefully.py +23 -151
  110. webscout/__init__.py +4 -2
  111. webscout/cli.py +3 -28
  112. webscout/conversation.py +35 -35
  113. webscout/litagent/Readme.md +276 -0
  114. webscout/scout/README.md +402 -0
  115. webscout/swiftcli/Readme.md +323 -0
  116. webscout/version.py +1 -1
  117. webscout/webscout_search.py +2 -182
  118. webscout/webscout_search_async.py +1 -179
  119. webscout/zeroart/README.md +89 -0
  120. webscout/zeroart/__init__.py +134 -54
  121. webscout/zeroart/base.py +19 -13
  122. webscout/zeroart/effects.py +101 -99
  123. webscout/zeroart/fonts.py +1239 -816
  124. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/METADATA +116 -74
  125. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/RECORD +130 -103
  126. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/WHEEL +1 -1
  127. webscout-8.2.8.dist-info/entry_points.txt +3 -0
  128. webscout-8.2.8.dist-info/top_level.txt +1 -0
  129. webscout/Provider/AISEARCH/ISou.py +0 -256
  130. webscout/Provider/ElectronHub.py +0 -773
  131. webscout/Provider/Free2GPT.py +0 -241
  132. webscout/Provider/GPTWeb.py +0 -249
  133. webscout/Provider/bagoodex.py +0 -145
  134. webscout/Provider/geminiprorealtime.py +0 -160
  135. webscout/scout/core.py +0 -881
  136. webscout-8.2.6.dist-info/entry_points.txt +0 -3
  137. webscout-8.2.6.dist-info/top_level.txt +0 -2
  138. webstoken/__init__.py +0 -30
  139. webstoken/classifier.py +0 -189
  140. webstoken/keywords.py +0 -216
  141. webstoken/language.py +0 -128
  142. webstoken/ner.py +0 -164
  143. webstoken/normalizer.py +0 -35
  144. webstoken/processor.py +0 -77
  145. webstoken/sentiment.py +0 -206
  146. webstoken/stemmer.py +0 -73
  147. webstoken/tagger.py +0 -60
  148. webstoken/tokenizer.py +0 -158
  149. /webscout/Provider/{Youchat.py → UNFINISHED/Youchat.py} +0 -0
  150. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/licenses/LICENSE.md +0 -0
webscout/scout/core.py DELETED
@@ -1,881 +0,0 @@
1
- """
2
- Scout - The next-gen web scraping library! 🚀
3
- A powerful, flexible, and performant HTML parsing library.
4
- Enhanced with advanced features and intelligent parsing.
5
- """
6
-
7
- import re
8
- import json
9
- import hashlib
10
- import unicodedata
11
- import requests
12
- from markdownify import MarkdownConverter
13
- import concurrent.futures
14
- import urllib.parse
15
- from collections import Counter
16
- from typing import Union, List, Dict, Optional, Callable, Any, Iterator, Set
17
-
18
- from .parsers.html_parser import HTMLParser
19
- from .parsers.lxml_parser import LXMLParser
20
- from .parsers.html5lib_parser import HTML5Parser
21
- from .element import Tag, NavigableString
22
- from .utils import decode_markup
23
-
24
- class ScoutTextAnalyzer:
25
- """
26
- Advanced text analysis and processing utility.
27
- """
28
- @staticmethod
29
- def tokenize(text: str, lowercase=True, remove_punctuation=True) -> List[str]:
30
- """
31
- Tokenize text into words.
32
-
33
- Args:
34
- text (str): Input text
35
- lowercase (bool, optional): Convert to lowercase
36
- remove_punctuation (bool, optional): Remove punctuation
37
-
38
- Returns:
39
- List[str]: List of tokens
40
- """
41
- if lowercase:
42
- text = text.lower()
43
-
44
- if remove_punctuation:
45
- text = re.sub(r'[^\w\s]', '', text)
46
-
47
- return text.split()
48
-
49
- @staticmethod
50
- def count_words(text: str) -> Dict[str, int]:
51
- """
52
- Count word frequencies.
53
-
54
- Args:
55
- text (str): Input text
56
-
57
- Returns:
58
- Dict[str, int]: Word frequency dictionary
59
- """
60
- return dict(Counter(ScoutTextAnalyzer.tokenize(text)))
61
-
62
- @staticmethod
63
- def extract_entities(text: str) -> Dict[str, Set[str]]:
64
- """
65
- Extract named entities from text.
66
-
67
- Args:
68
- text (str): Input text
69
-
70
- Returns:
71
- Dict[str, Set[str]]: Extracted entities
72
- """
73
- entities = {
74
- 'emails': set(re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)),
75
- 'urls': set(re.findall(r'https?://\S+', text)),
76
- 'phones': set(re.findall(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', text)),
77
- 'dates': set(re.findall(r'\b\d{1,2}[-/]\d{1,2}[-/]\d{2,4}\b', text))
78
- }
79
- return entities
80
-
81
- class ScoutWebAnalyzer:
82
- """
83
- Advanced web content analysis utility.
84
- """
85
- @staticmethod
86
- def analyze_page_structure(scout_obj: 'Scout') -> Dict[str, Any]:
87
- """
88
- Analyze the structure of a web page.
89
-
90
- Args:
91
- scout_obj (Scout): Parsed Scout object
92
-
93
- Returns:
94
- Dict[str, Any]: Page structure analysis
95
- """
96
- analysis = {
97
- 'tag_distribution': {},
98
- 'class_distribution': {},
99
- 'id_distribution': {},
100
- 'depth_analysis': {}
101
- }
102
-
103
- # Tag distribution
104
- for tag in scout_obj.find_all():
105
- analysis['tag_distribution'][tag.name] = analysis['tag_distribution'].get(tag.name, 0) + 1
106
-
107
- # Class distribution
108
- for tag in scout_obj.find_all(attrs={'class': True}):
109
- for cls in tag.get('class', []):
110
- analysis['class_distribution'][cls] = analysis['class_distribution'].get(cls, 0) + 1
111
-
112
- # ID distribution
113
- for tag in scout_obj.find_all(attrs={'id': True}):
114
- analysis['id_distribution'][tag.get('id')] = analysis['id_distribution'].get(tag.get('id'), 0) + 1
115
-
116
- # Depth analysis
117
- def _analyze_depth(tag, current_depth=0):
118
- analysis['depth_analysis'][current_depth] = analysis['depth_analysis'].get(current_depth, 0) + 1
119
- for child in tag.contents:
120
- if isinstance(child, Tag):
121
- _analyze_depth(child, current_depth + 1)
122
-
123
- _analyze_depth(scout_obj._soup)
124
-
125
- return analysis
126
-
127
- class ScoutSearchResult:
128
- """
129
- Represents a search result with advanced querying capabilities.
130
- Enhanced with more intelligent filtering and processing.
131
- """
132
- def __init__(self, results: List[Tag]):
133
- """
134
- Initialize a search result collection.
135
-
136
- Args:
137
- results (List[Tag]): List of matching tags
138
- """
139
- self._results = results
140
-
141
- def __len__(self) -> int:
142
- return len(self._results)
143
-
144
- def __iter__(self) -> Iterator[Tag]:
145
- return iter(self._results)
146
-
147
- def __getitem__(self, index: Union[int, slice]) -> Union[Tag, List[Tag]]:
148
- return self._results[index]
149
-
150
- def texts(self, separator=' ', strip=True) -> List[str]:
151
- """
152
- Extract texts from all results.
153
-
154
- Args:
155
- separator (str, optional): Text separator
156
- strip (bool, optional): Strip whitespace
157
-
158
- Returns:
159
- List[str]: List of extracted texts
160
- """
161
- return [tag.get_text(separator, strip) for tag in self._results]
162
-
163
- def attrs(self, attr_name: str) -> List[Any]:
164
- """
165
- Extract a specific attribute from all results.
166
-
167
- Args:
168
- attr_name (str): Attribute name to extract
169
-
170
- Returns:
171
- List[Any]: List of attribute values
172
- """
173
- return [tag.get(attr_name) for tag in self._results]
174
-
175
- def filter(self, predicate: Callable[[Tag], bool]) -> 'ScoutSearchResult':
176
- """
177
- Filter results using a predicate function.
178
-
179
- Args:
180
- predicate (Callable[[Tag], bool]): Filtering function
181
-
182
- Returns:
183
- ScoutSearchResult: Filtered search results
184
- """
185
- return ScoutSearchResult([tag for tag in self._results if predicate(tag)])
186
-
187
- def map(self, transform: Callable[[Tag], Any]) -> List[Any]:
188
- """
189
- Transform results using a mapping function.
190
-
191
- Args:
192
- transform (Callable[[Tag], Any]): Transformation function
193
-
194
- Returns:
195
- List[Any]: Transformed results
196
- """
197
- return [transform(tag) for tag in self._results]
198
-
199
- def analyze_text(self) -> Dict[str, Any]:
200
- """
201
- Perform text analysis on search results.
202
-
203
- Returns:
204
- Dict[str, Any]: Text analysis results
205
- """
206
- texts = self.texts(strip=True)
207
- full_text = ' '.join(texts)
208
-
209
- return {
210
- 'total_results': len(self._results),
211
- 'word_count': ScoutTextAnalyzer.count_words(full_text),
212
- 'entities': ScoutTextAnalyzer.extract_entities(full_text)
213
- }
214
-
215
- class ScoutCrawler:
216
- """
217
- Advanced web crawling utility for Scout library.
218
- """
219
- def __init__(self, base_url: str, max_depth: int = 3, max_pages: int = 50):
220
- """
221
- Initialize the web crawler.
222
-
223
- Args:
224
- base_url (str): Starting URL to crawl
225
- max_depth (int, optional): Maximum crawl depth
226
- max_pages (int, optional): Maximum number of pages to crawl
227
- """
228
- self.base_url = base_url
229
- self.max_depth = max_depth
230
- self.max_pages = max_pages
231
- self.visited_urls = set()
232
- self.crawled_pages = []
233
-
234
- def _is_valid_url(self, url: str) -> bool:
235
- """
236
- Check if a URL is valid and within the same domain.
237
-
238
- Args:
239
- url (str): URL to validate
240
-
241
- Returns:
242
- bool: Whether the URL is valid
243
- """
244
- try:
245
- parsed_base = urllib.parse.urlparse(self.base_url)
246
- parsed_url = urllib.parse.urlparse(url)
247
-
248
- return (
249
- parsed_url.scheme in ['http', 'https'] and
250
- parsed_base.netloc == parsed_url.netloc and
251
- len(self.visited_urls) < self.max_pages
252
- )
253
- except Exception:
254
- return False
255
-
256
- def _crawl_page(self, url: str, depth: int = 0) -> Dict[str, Union[str, List[str]]]:
257
- """
258
- Crawl a single page and extract information.
259
-
260
- Args:
261
- url (str): URL to crawl
262
- depth (int, optional): Current crawl depth
263
-
264
- Returns:
265
- Dict[str, Union[str, List[str]]]: Crawled page information
266
- """
267
- if depth > self.max_depth or url in self.visited_urls:
268
- return {}
269
-
270
- try:
271
- response = requests.get(url, timeout=10)
272
- response.raise_for_status()
273
-
274
- scout = Scout(response.text, features='lxml')
275
-
276
- page_info = {
277
- 'url': url,
278
- 'title': scout.find('title').get_text() if scout.find('title') else '',
279
- 'links': [
280
- urllib.parse.urljoin(url, link.get('href'))
281
- for link in scout.find_all('a', href=True)
282
- if self._is_valid_url(urllib.parse.urljoin(url, link.get('href')))
283
- ],
284
- 'text': scout.get_text(),
285
- 'markdown': scout.to_markdown()
286
- }
287
-
288
- self.visited_urls.add(url)
289
- self.crawled_pages.append(page_info)
290
-
291
- return page_info
292
- except Exception as e:
293
- print(f"Error crawling {url}: {e}")
294
- return {}
295
-
296
- def crawl(self) -> List[Dict[str, Union[str, List[str]]]]:
297
- """
298
- Start web crawling from base URL.
299
-
300
- Returns:
301
- List[Dict[str, Union[str, List[str]]]]: List of crawled pages
302
- """
303
- with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
304
- futures = {executor.submit(self._crawl_page, self.base_url, 0)}
305
-
306
- while futures:
307
- done, futures = concurrent.futures.wait(
308
- futures, return_when=concurrent.futures.FIRST_COMPLETED
309
- )
310
-
311
- for future in done:
312
- page_info = future.result()
313
-
314
- for link in page_info.get('links', []):
315
- if link not in self.visited_urls:
316
- futures.add(
317
- executor.submit(
318
- self._crawl_page,
319
- link,
320
- self.visited_urls.count(self.base_url) + 1
321
- )
322
- )
323
-
324
- return self.crawled_pages
325
-
326
- class Scout:
327
- """
328
- Scout - Making web scraping a breeze! 🌊
329
- A comprehensive HTML parsing and traversal library.
330
- Enhanced with advanced features and intelligent parsing.
331
- """
332
-
333
- # Available parsers - choose your weapon! ⚔️
334
- PARSERS = {
335
- 'html.parser': HTMLParser,
336
- 'lxml': LXMLParser,
337
- 'html5lib': HTML5Parser,
338
- 'lxml-xml': LXMLParser, # For XML parsing
339
- }
340
-
341
- def __init__(self, markup="", features='html.parser', from_encoding=None, **kwargs):
342
- """
343
- Initialize Scout with HTML content.
344
-
345
- Args:
346
- markup (str): HTML content to parse
347
- features (str): Parser to use ('html.parser', 'lxml', 'html5lib', 'lxml-xml')
348
- from_encoding (str): Source encoding (if known)
349
- **kwargs: Additional parsing options
350
- """
351
- # Intelligent markup handling
352
- self.markup = self._preprocess_markup(markup, from_encoding)
353
- self.features = features
354
- self.from_encoding = from_encoding
355
-
356
- # Get the right parser for the job
357
- if features not in self.PARSERS:
358
- raise ValueError(
359
- f"Invalid parser '{features}'! Choose from: {', '.join(self.PARSERS.keys())}"
360
- )
361
-
362
- parser_class = self.PARSERS[features]
363
- self.parser = parser_class()
364
-
365
- # Parse that HTML! 🎯
366
- self._soup = self.parser.parse(self.markup)
367
-
368
- # BeautifulSoup-like attributes
369
- self.name = self._soup.name if hasattr(self._soup, 'name') else None
370
- self.attrs = self._soup.attrs if hasattr(self._soup, 'attrs') else {}
371
-
372
- # Advanced parsing options
373
- self._cache = {}
374
-
375
- # Text and web analyzers
376
- self.text_analyzer = ScoutTextAnalyzer()
377
- self.web_analyzer = ScoutWebAnalyzer()
378
-
379
- def normalize_text(self, text: str, form='NFKD') -> str:
380
- """
381
- Normalize text using Unicode normalization.
382
-
383
- Args:
384
- text (str): Input text
385
- form (str, optional): Normalization form
386
-
387
- Returns:
388
- str: Normalized text
389
- """
390
- return unicodedata.normalize(form, text)
391
-
392
- def url_parse(self, url: str) -> Dict[str, str]:
393
- """
394
- Parse and analyze a URL.
395
-
396
- Args:
397
- url (str): URL to parse
398
-
399
- Returns:
400
- Dict[str, str]: Parsed URL components
401
- """
402
- parsed = urllib.parse.urlparse(url)
403
- return {
404
- 'scheme': parsed.scheme,
405
- 'netloc': parsed.netloc,
406
- 'path': parsed.path,
407
- 'params': parsed.params,
408
- 'query': parsed.query,
409
- 'fragment': parsed.fragment
410
- }
411
-
412
- def analyze_page_structure(self) -> Dict[str, Any]:
413
- """
414
- Analyze the structure of the parsed page.
415
-
416
- Returns:
417
- Dict[str, Any]: Page structure analysis
418
- """
419
- return self.web_analyzer.analyze_page_structure(self)
420
-
421
- def analyze_text(self, text: Optional[str] = None) -> Dict[str, Any]:
422
- """
423
- Perform advanced text analysis.
424
-
425
- Args:
426
- text (str, optional): Text to analyze. If None, uses page text.
427
-
428
- Returns:
429
- Dict[str, Any]: Text analysis results
430
- """
431
- if text is None:
432
- text = self.get_text()
433
-
434
- return {
435
- 'word_count': self.text_analyzer.count_words(text),
436
- 'entities': self.text_analyzer.extract_entities(text),
437
- 'tokens': self.text_analyzer.tokenize(text)
438
- }
439
-
440
- def extract_semantic_info(self) -> Dict[str, Any]:
441
- """
442
- Extract semantic information from the document.
443
-
444
- Returns:
445
- Dict[str, Any]: Semantic information
446
- """
447
- semantic_info = {
448
- 'headings': {
449
- 'h1': [h.get_text(strip=True) for h in self.find_all('h1')],
450
- 'h2': [h.get_text(strip=True) for h in self.find_all('h2')],
451
- 'h3': [h.get_text(strip=True) for h in self.find_all('h3')]
452
- },
453
- 'lists': {
454
- 'ul': [ul.find_all('li') for ul in self.find_all('ul')],
455
- 'ol': [ol.find_all('li') for ol in self.find_all('ol')]
456
- },
457
- 'tables': {
458
- 'count': len(self.find_all('table')),
459
- 'headers': [table.find_all('th') for table in self.find_all('table')]
460
- }
461
- }
462
- return semantic_info
463
-
464
- def cache(self, key: str, value: Any = None) -> Any:
465
- """
466
- Manage a cache for parsed content.
467
-
468
- Args:
469
- key (str): Cache key
470
- value (Any, optional): Value to cache
471
-
472
- Returns:
473
- Any: Cached value or None
474
- """
475
- if value is not None:
476
- self._cache[key] = value
477
- return self._cache.get(key)
478
-
479
- def hash_content(self, method='md5') -> str:
480
- """
481
- Generate a hash of the parsed content.
482
-
483
- Args:
484
- method (str, optional): Hashing method
485
-
486
- Returns:
487
- str: Content hash
488
- """
489
- hash_methods = {
490
- 'md5': hashlib.md5,
491
- 'sha1': hashlib.sha1,
492
- 'sha256': hashlib.sha256
493
- }
494
-
495
- if method not in hash_methods:
496
- raise ValueError(f"Unsupported hash method: {method}")
497
-
498
- hasher = hash_methods[method]()
499
- hasher.update(str(self._soup).encode('utf-8'))
500
- return hasher.hexdigest()
501
-
502
- def extract_links(self, base_url: Optional[str] = None) -> List[Dict[str, str]]:
503
- """
504
- Extract all links from the document.
505
-
506
- Args:
507
- base_url (str, optional): Base URL for resolving relative links
508
-
509
- Returns:
510
- List[Dict[str, str]]: List of link dictionaries
511
- """
512
- links = []
513
- for link in self.find_all(['a', 'link']):
514
- href = link.get('href')
515
- if href:
516
- # Resolve relative URLs if base_url is provided
517
- if base_url and not href.startswith(('http://', 'https://', '//')):
518
- href = f"{base_url.rstrip('/')}/{href.lstrip('/')}"
519
-
520
- links.append({
521
- 'href': href,
522
- 'text': link.get_text(strip=True),
523
- 'rel': link.get('rel', [None])[0],
524
- 'type': link.get('type')
525
- })
526
- return links
527
-
528
- def extract_metadata(self) -> Dict[str, Any]:
529
- """
530
- Extract metadata from HTML document.
531
-
532
- Returns:
533
- Dict[str, Any]: Extracted metadata
534
- """
535
- metadata = {
536
- 'title': self.find('title').get_text() if self.find('title') else None,
537
- 'description': self.find('meta', attrs={'name': 'description'}).get('content') if self.find('meta', attrs={'name': 'description'}) else None,
538
- 'keywords': self.find('meta', attrs={'name': 'keywords'}).get('content', '').split(',') if self.find('meta', attrs={'name': 'keywords'}) else [],
539
- 'og_metadata': {},
540
- 'twitter_metadata': {}
541
- }
542
-
543
- # Open Graph metadata
544
- for meta in self.find_all('meta', attrs={'property': re.compile(r'^og:')}):
545
- key = meta.get('property')[3:]
546
- metadata['og_metadata'][key] = meta.get('content')
547
-
548
- # Twitter Card metadata
549
- for meta in self.find_all('meta', attrs={'name': re.compile(r'^twitter:')}):
550
- key = meta.get('name')[8:]
551
- metadata['twitter_metadata'][key] = meta.get('content')
552
-
553
- return metadata
554
-
555
- def to_json(self, indent=2) -> str:
556
- """
557
- Convert parsed content to JSON.
558
-
559
- Args:
560
- indent (int, optional): JSON indentation
561
-
562
- Returns:
563
- str: JSON representation of the document
564
- """
565
- def _tag_to_dict(tag):
566
- if isinstance(tag, NavigableString):
567
- return str(tag)
568
-
569
- result = {
570
- 'name': tag.name,
571
- 'attrs': tag.attrs,
572
- 'text': tag.get_text(strip=True)
573
- }
574
-
575
- if tag.contents:
576
- result['children'] = [_tag_to_dict(child) for child in tag.contents]
577
-
578
- return result
579
-
580
- return json.dumps(_tag_to_dict(self._soup), indent=indent)
581
-
582
- def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs) -> Optional[Tag]:
583
- """
584
- Find the first matching element.
585
-
586
- Args:
587
- name (str, optional): Tag name to search for
588
- attrs (dict, optional): Attributes to match
589
- recursive (bool, optional): Search recursively
590
- text (str, optional): Text content to match
591
-
592
- Returns:
593
- Tag or None: First matching element
594
- """
595
- result = self._soup.find(name, attrs, recursive, text, **kwargs)
596
- return ScoutSearchResult([result]) if result else ScoutSearchResult([])
597
-
598
- def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs) -> ScoutSearchResult:
599
- """
600
- Find all matching elements.
601
-
602
- Args:
603
- name (str, optional): Tag name to search for
604
- attrs (dict, optional): Attributes to match
605
- recursive (bool, optional): Search recursively
606
- text (str, optional): Text content to match
607
- limit (int, optional): Maximum number of results
608
-
609
- Returns:
610
- ScoutSearchResult: List of matching elements
611
- """
612
- results = self._soup.find_all(name, attrs, recursive, text, limit, **kwargs)
613
- return ScoutSearchResult(results)
614
-
615
- def find_parent(self, name=None, attrs={}, **kwargs):
616
- """
617
- Find the first parent matching given criteria.
618
-
619
- Args:
620
- name (str, optional): Tag name to search for
621
- attrs (dict, optional): Attributes to match
622
-
623
- Returns:
624
- Tag or None: First matching parent
625
- """
626
- current = self._soup.parent
627
- while current:
628
- if (name is None or current.name == name) and \
629
- all(current.get(k) == v for k, v in attrs.items()):
630
- return current
631
- current = current.parent
632
- return None
633
-
634
- def find_parents(self, name=None, attrs={}, limit=None, **kwargs):
635
- """
636
- Find all parents matching given criteria.
637
-
638
- Args:
639
- name (str, optional): Tag name to search for
640
- attrs (dict, optional): Attributes to match
641
- limit (int, optional): Maximum number of results
642
-
643
- Returns:
644
- List[Tag]: List of matching parents
645
- """
646
- parents = []
647
- current = self._soup.parent
648
- while current and (limit is None or len(parents) < limit):
649
- if (name is None or current.name == name) and \
650
- all(current.get(k) == v for k, v in attrs.items()):
651
- parents.append(current)
652
- current = current.parent
653
- return parents
654
-
655
- def find_next_sibling(self, name=None, attrs={}, **kwargs):
656
- """
657
- Find the next sibling matching given criteria.
658
-
659
- Args:
660
- name (str, optional): Tag name to search for
661
- attrs (dict, optional): Attributes to match
662
-
663
- Returns:
664
- Tag or None: First matching next sibling
665
- """
666
- if not self._soup.parent:
667
- return None
668
-
669
- siblings = self._soup.parent.contents
670
- try:
671
- current_index = siblings.index(self._soup)
672
- for sibling in siblings[current_index + 1:]:
673
- if isinstance(sibling, Tag):
674
- if (name is None or sibling.name == name) and \
675
- all(sibling.get(k) == v for k, v in attrs.items()):
676
- return sibling
677
- except ValueError:
678
- pass
679
- return None
680
-
681
- def find_next_siblings(self, name=None, attrs={}, limit=None, **kwargs):
682
- """
683
- Find all next siblings matching given criteria.
684
-
685
- Args:
686
- name (str, optional): Tag name to search for
687
- attrs (dict, optional): Attributes to match
688
- limit (int, optional): Maximum number of results
689
-
690
- Returns:
691
- List[Tag]: List of matching next siblings
692
- """
693
- if not self._soup.parent:
694
- return []
695
-
696
- siblings = []
697
- siblings_list = self._soup.parent.contents
698
- try:
699
- current_index = siblings_list.index(self._soup)
700
- for sibling in siblings_list[current_index + 1:]:
701
- if isinstance(sibling, Tag):
702
- if (name is None or sibling.name == name) and \
703
- all(sibling.get(k) == v for k, v in attrs.items()):
704
- siblings.append(sibling)
705
- if limit and len(siblings) == limit:
706
- break
707
- except ValueError:
708
- pass
709
- return siblings
710
-
711
- def select(self, selector: str) -> List[Tag]:
712
- """
713
- Select elements using CSS selector.
714
-
715
- Args:
716
- selector (str): CSS selector string
717
-
718
- Returns:
719
- List[Tag]: List of matching elements
720
- """
721
- return self._soup.select(selector)
722
-
723
- def select_one(self, selector: str) -> Optional[Tag]:
724
- """
725
- Select the first element matching the CSS selector.
726
-
727
- Args:
728
- selector (str): CSS selector string
729
-
730
- Returns:
731
- Tag or None: First matching element
732
- """
733
- return self._soup.select_one(selector)
734
-
735
- def get_text(self, separator=' ', strip=False, types=None) -> str:
736
- """
737
- Extract all text from the parsed document.
738
-
739
- Args:
740
- separator (str, optional): Text separator
741
- strip (bool, optional): Strip whitespace
742
- types (list, optional): Types of content to extract
743
-
744
- Returns:
745
- str: Extracted text
746
- """
747
- return self._soup.get_text(separator, strip, types)
748
-
749
- def prettify(self, formatter='minimal') -> str:
750
- """
751
- Return a formatted, pretty-printed version of the HTML.
752
-
753
- Args:
754
- formatter (str, optional): Formatting style
755
-
756
- Returns:
757
- str: Prettified HTML
758
- """
759
- return self._soup.prettify(formatter)
760
-
761
- def decompose(self, tag: Tag = None) -> None:
762
- """
763
- Remove a tag and its contents from the document.
764
-
765
- Args:
766
- tag (Tag, optional): Tag to remove. If None, removes the root tag.
767
- """
768
- if tag is None:
769
- tag = self._soup
770
- tag.decompose()
771
-
772
- def extract(self, tag: Tag = None) -> Tag:
773
- """
774
- Remove a tag from the document and return it.
775
-
776
- Args:
777
- tag (Tag, optional): Tag to extract. If None, extracts the root tag.
778
-
779
- Returns:
780
- Tag: Extracted tag
781
- """
782
- if tag is None:
783
- tag = self._soup
784
- return tag.extract()
785
-
786
- def clear(self, tag: Tag = None) -> None:
787
- """
788
- Remove a tag's contents while keeping the tag itself.
789
-
790
- Args:
791
- tag (Tag, optional): Tag to clear. If None, clears the root tag.
792
- """
793
- if tag is None:
794
- tag = self._soup
795
- tag.clear()
796
-
797
- def replace_with(self, old_tag: Tag, new_tag: Tag) -> None:
798
- """
799
- Replace one tag with another.
800
-
801
- Args:
802
- old_tag (Tag): Tag to replace
803
- new_tag (Tag): Replacement tag
804
- """
805
- old_tag.replace_with(new_tag)
806
-
807
- def encode(self, encoding='utf-8') -> bytes:
808
- """
809
- Encode the document to a specific encoding.
810
-
811
- Args:
812
- encoding (str, optional): Encoding to use
813
-
814
- Returns:
815
- bytes: Encoded document
816
- """
817
- return str(self._soup).encode(encoding)
818
-
819
- def decode(self, encoding='utf-8') -> str:
820
- """
821
- Decode the document from a specific encoding.
822
-
823
- Args:
824
- encoding (str, optional): Encoding to use
825
-
826
- Returns:
827
- str: Decoded document
828
- """
829
- return str(self._soup)
830
-
831
- def __str__(self) -> str:
832
- """
833
- String representation of the parsed document.
834
-
835
- Returns:
836
- str: HTML content
837
- """
838
- return str(self._soup)
839
-
840
- def __repr__(self) -> str:
841
- """
842
- Detailed representation of the Scout object.
843
-
844
- Returns:
845
- str: Scout object description
846
- """
847
- return f"Scout(features='{self.features}', content_length={len(self.markup)})"
848
-
849
- def _preprocess_markup(self, markup: str, encoding: Optional[str] = None) -> str:
850
- """
851
- Preprocess markup before parsing.
852
-
853
- Args:
854
- markup (str): Input markup
855
- encoding (str, optional): Encoding to use
856
-
857
- Returns:
858
- str: Preprocessed markup
859
- """
860
- # Decode markup
861
- decoded_markup = decode_markup(markup, encoding)
862
-
863
- # Basic HTML cleaning
864
- # Remove comments, normalize whitespace, etc.
865
- decoded_markup = re.sub(r'<!--.*?-->', '', decoded_markup, flags=re.DOTALL)
866
- decoded_markup = re.sub(r'\s+', ' ', decoded_markup)
867
-
868
- return decoded_markup
869
-
870
- def to_markdown(self, heading_style='ATX') -> str:
871
- """
872
- Convert HTML to Markdown.
873
-
874
- Args:
875
- heading_style (str, optional): Markdown heading style
876
-
877
- Returns:
878
- str: Markdown representation of the document
879
- """
880
- converter = MarkdownConverter(heading_style=heading_style)
881
- return converter.convert(str(self._soup))