webscout 8.2.6__py3-none-any.whl → 8.2.7__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 (292) hide show
  1. webscout/AIutel.py +97 -87
  2. webscout/version.py +1 -1
  3. {webscout-8.2.6.dist-info → webscout-8.2.7.dist-info}/METADATA +2 -15
  4. webscout-8.2.7.dist-info/RECORD +26 -0
  5. {webscout-8.2.6.dist-info → webscout-8.2.7.dist-info}/WHEEL +1 -1
  6. webscout-8.2.7.dist-info/entry_points.txt +3 -0
  7. webscout-8.2.7.dist-info/top_level.txt +1 -0
  8. webscout/Extra/GitToolkit/__init__.py +0 -10
  9. webscout/Extra/GitToolkit/gitapi/__init__.py +0 -12
  10. webscout/Extra/GitToolkit/gitapi/repository.py +0 -195
  11. webscout/Extra/GitToolkit/gitapi/user.py +0 -96
  12. webscout/Extra/GitToolkit/gitapi/utils.py +0 -62
  13. webscout/Extra/YTToolkit/YTdownloader.py +0 -957
  14. webscout/Extra/YTToolkit/__init__.py +0 -3
  15. webscout/Extra/YTToolkit/transcriber.py +0 -476
  16. webscout/Extra/YTToolkit/ytapi/__init__.py +0 -6
  17. webscout/Extra/YTToolkit/ytapi/channel.py +0 -307
  18. webscout/Extra/YTToolkit/ytapi/errors.py +0 -13
  19. webscout/Extra/YTToolkit/ytapi/extras.py +0 -45
  20. webscout/Extra/YTToolkit/ytapi/https.py +0 -88
  21. webscout/Extra/YTToolkit/ytapi/patterns.py +0 -61
  22. webscout/Extra/YTToolkit/ytapi/playlist.py +0 -59
  23. webscout/Extra/YTToolkit/ytapi/pool.py +0 -8
  24. webscout/Extra/YTToolkit/ytapi/query.py +0 -40
  25. webscout/Extra/YTToolkit/ytapi/stream.py +0 -63
  26. webscout/Extra/YTToolkit/ytapi/utils.py +0 -62
  27. webscout/Extra/YTToolkit/ytapi/video.py +0 -232
  28. webscout/Extra/__init__.py +0 -7
  29. webscout/Extra/autocoder/__init__.py +0 -9
  30. webscout/Extra/autocoder/autocoder.py +0 -910
  31. webscout/Extra/autocoder/autocoder_utiles.py +0 -332
  32. webscout/Extra/gguf.py +0 -684
  33. webscout/Extra/tempmail/__init__.py +0 -28
  34. webscout/Extra/tempmail/async_utils.py +0 -141
  35. webscout/Extra/tempmail/base.py +0 -161
  36. webscout/Extra/tempmail/cli.py +0 -187
  37. webscout/Extra/tempmail/emailnator.py +0 -84
  38. webscout/Extra/tempmail/mail_tm.py +0 -361
  39. webscout/Extra/tempmail/temp_mail_io.py +0 -292
  40. webscout/Extra/weather.py +0 -194
  41. webscout/Extra/weather_ascii.py +0 -76
  42. webscout/Litlogger/__init__.py +0 -67
  43. webscout/Litlogger/core/__init__.py +0 -6
  44. webscout/Litlogger/core/level.py +0 -23
  45. webscout/Litlogger/core/logger.py +0 -165
  46. webscout/Litlogger/handlers/__init__.py +0 -12
  47. webscout/Litlogger/handlers/console.py +0 -33
  48. webscout/Litlogger/handlers/file.py +0 -143
  49. webscout/Litlogger/handlers/network.py +0 -173
  50. webscout/Litlogger/styles/__init__.py +0 -7
  51. webscout/Litlogger/styles/colors.py +0 -249
  52. webscout/Litlogger/styles/formats.py +0 -458
  53. webscout/Litlogger/styles/text.py +0 -87
  54. webscout/Litlogger/utils/__init__.py +0 -6
  55. webscout/Litlogger/utils/detectors.py +0 -153
  56. webscout/Litlogger/utils/formatters.py +0 -200
  57. webscout/Provider/AI21.py +0 -177
  58. webscout/Provider/AISEARCH/DeepFind.py +0 -250
  59. webscout/Provider/AISEARCH/ISou.py +0 -256
  60. webscout/Provider/AISEARCH/Perplexity.py +0 -359
  61. webscout/Provider/AISEARCH/__init__.py +0 -10
  62. webscout/Provider/AISEARCH/felo_search.py +0 -228
  63. webscout/Provider/AISEARCH/genspark_search.py +0 -208
  64. webscout/Provider/AISEARCH/hika_search.py +0 -198
  65. webscout/Provider/AISEARCH/iask_search.py +0 -436
  66. webscout/Provider/AISEARCH/monica_search.py +0 -246
  67. webscout/Provider/AISEARCH/scira_search.py +0 -322
  68. webscout/Provider/AISEARCH/webpilotai_search.py +0 -281
  69. webscout/Provider/Aitopia.py +0 -316
  70. webscout/Provider/AllenAI.py +0 -447
  71. webscout/Provider/Andi.py +0 -228
  72. webscout/Provider/Blackboxai.py +0 -229
  73. webscout/Provider/ChatGPTClone.py +0 -237
  74. webscout/Provider/ChatGPTGratis.py +0 -194
  75. webscout/Provider/ChatSandbox.py +0 -342
  76. webscout/Provider/Cloudflare.py +0 -325
  77. webscout/Provider/Cohere.py +0 -208
  78. webscout/Provider/Deepinfra.py +0 -338
  79. webscout/Provider/ElectronHub.py +0 -773
  80. webscout/Provider/ExaAI.py +0 -261
  81. webscout/Provider/ExaChat.py +0 -358
  82. webscout/Provider/Free2GPT.py +0 -241
  83. webscout/Provider/GPTWeb.py +0 -249
  84. webscout/Provider/Gemini.py +0 -169
  85. webscout/Provider/GithubChat.py +0 -370
  86. webscout/Provider/GizAI.py +0 -285
  87. webscout/Provider/Glider.py +0 -222
  88. webscout/Provider/Groq.py +0 -801
  89. webscout/Provider/HF_space/__init__.py +0 -0
  90. webscout/Provider/HF_space/qwen_qwen2.py +0 -206
  91. webscout/Provider/HeckAI.py +0 -257
  92. webscout/Provider/HuggingFaceChat.py +0 -469
  93. webscout/Provider/Hunyuan.py +0 -283
  94. webscout/Provider/Jadve.py +0 -291
  95. webscout/Provider/Koboldai.py +0 -381
  96. webscout/Provider/LambdaChat.py +0 -411
  97. webscout/Provider/Llama3.py +0 -259
  98. webscout/Provider/MCPCore.py +0 -315
  99. webscout/Provider/Marcus.py +0 -206
  100. webscout/Provider/Nemotron.py +0 -218
  101. webscout/Provider/Netwrck.py +0 -270
  102. webscout/Provider/OLLAMA.py +0 -396
  103. webscout/Provider/OPENAI/__init__.py +0 -28
  104. webscout/Provider/OPENAI/ai4chat.py +0 -286
  105. webscout/Provider/OPENAI/base.py +0 -46
  106. webscout/Provider/OPENAI/c4ai.py +0 -367
  107. webscout/Provider/OPENAI/chatgpt.py +0 -549
  108. webscout/Provider/OPENAI/chatgptclone.py +0 -481
  109. webscout/Provider/OPENAI/deepinfra.py +0 -309
  110. webscout/Provider/OPENAI/e2b.py +0 -1350
  111. webscout/Provider/OPENAI/exaai.py +0 -404
  112. webscout/Provider/OPENAI/exachat.py +0 -437
  113. webscout/Provider/OPENAI/freeaichat.py +0 -352
  114. webscout/Provider/OPENAI/glider.py +0 -316
  115. webscout/Provider/OPENAI/groq.py +0 -354
  116. webscout/Provider/OPENAI/heckai.py +0 -341
  117. webscout/Provider/OPENAI/llmchatco.py +0 -327
  118. webscout/Provider/OPENAI/mcpcore.py +0 -376
  119. webscout/Provider/OPENAI/multichat.py +0 -368
  120. webscout/Provider/OPENAI/netwrck.py +0 -350
  121. webscout/Provider/OPENAI/opkfc.py +0 -488
  122. webscout/Provider/OPENAI/scirachat.py +0 -462
  123. webscout/Provider/OPENAI/sonus.py +0 -294
  124. webscout/Provider/OPENAI/standardinput.py +0 -425
  125. webscout/Provider/OPENAI/textpollinations.py +0 -329
  126. webscout/Provider/OPENAI/toolbaz.py +0 -406
  127. webscout/Provider/OPENAI/typegpt.py +0 -346
  128. webscout/Provider/OPENAI/uncovrAI.py +0 -455
  129. webscout/Provider/OPENAI/utils.py +0 -211
  130. webscout/Provider/OPENAI/venice.py +0 -413
  131. webscout/Provider/OPENAI/wisecat.py +0 -381
  132. webscout/Provider/OPENAI/writecream.py +0 -156
  133. webscout/Provider/OPENAI/x0gpt.py +0 -371
  134. webscout/Provider/OPENAI/yep.py +0 -327
  135. webscout/Provider/OpenGPT.py +0 -209
  136. webscout/Provider/Openai.py +0 -496
  137. webscout/Provider/PI.py +0 -429
  138. webscout/Provider/Perplexitylabs.py +0 -415
  139. webscout/Provider/QwenLM.py +0 -254
  140. webscout/Provider/Reka.py +0 -214
  141. webscout/Provider/StandardInput.py +0 -290
  142. webscout/Provider/TTI/AiForce/__init__.py +0 -22
  143. webscout/Provider/TTI/AiForce/async_aiforce.py +0 -224
  144. webscout/Provider/TTI/AiForce/sync_aiforce.py +0 -245
  145. webscout/Provider/TTI/FreeAIPlayground/__init__.py +0 -9
  146. webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +0 -181
  147. webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +0 -180
  148. webscout/Provider/TTI/ImgSys/__init__.py +0 -23
  149. webscout/Provider/TTI/ImgSys/async_imgsys.py +0 -202
  150. webscout/Provider/TTI/ImgSys/sync_imgsys.py +0 -195
  151. webscout/Provider/TTI/MagicStudio/__init__.py +0 -2
  152. webscout/Provider/TTI/MagicStudio/async_magicstudio.py +0 -111
  153. webscout/Provider/TTI/MagicStudio/sync_magicstudio.py +0 -109
  154. webscout/Provider/TTI/Nexra/__init__.py +0 -22
  155. webscout/Provider/TTI/Nexra/async_nexra.py +0 -286
  156. webscout/Provider/TTI/Nexra/sync_nexra.py +0 -258
  157. webscout/Provider/TTI/PollinationsAI/__init__.py +0 -23
  158. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +0 -311
  159. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +0 -265
  160. webscout/Provider/TTI/__init__.py +0 -12
  161. webscout/Provider/TTI/aiarta/__init__.py +0 -2
  162. webscout/Provider/TTI/aiarta/async_aiarta.py +0 -482
  163. webscout/Provider/TTI/aiarta/sync_aiarta.py +0 -440
  164. webscout/Provider/TTI/artbit/__init__.py +0 -22
  165. webscout/Provider/TTI/artbit/async_artbit.py +0 -155
  166. webscout/Provider/TTI/artbit/sync_artbit.py +0 -148
  167. webscout/Provider/TTI/fastflux/__init__.py +0 -22
  168. webscout/Provider/TTI/fastflux/async_fastflux.py +0 -261
  169. webscout/Provider/TTI/fastflux/sync_fastflux.py +0 -252
  170. webscout/Provider/TTI/huggingface/__init__.py +0 -22
  171. webscout/Provider/TTI/huggingface/async_huggingface.py +0 -199
  172. webscout/Provider/TTI/huggingface/sync_huggingface.py +0 -195
  173. webscout/Provider/TTI/piclumen/__init__.py +0 -23
  174. webscout/Provider/TTI/piclumen/async_piclumen.py +0 -268
  175. webscout/Provider/TTI/piclumen/sync_piclumen.py +0 -233
  176. webscout/Provider/TTI/pixelmuse/__init__.py +0 -4
  177. webscout/Provider/TTI/pixelmuse/async_pixelmuse.py +0 -249
  178. webscout/Provider/TTI/pixelmuse/sync_pixelmuse.py +0 -182
  179. webscout/Provider/TTI/talkai/__init__.py +0 -4
  180. webscout/Provider/TTI/talkai/async_talkai.py +0 -229
  181. webscout/Provider/TTI/talkai/sync_talkai.py +0 -207
  182. webscout/Provider/TTS/__init__.py +0 -8
  183. webscout/Provider/TTS/base.py +0 -159
  184. webscout/Provider/TTS/deepgram.py +0 -156
  185. webscout/Provider/TTS/elevenlabs.py +0 -111
  186. webscout/Provider/TTS/gesserit.py +0 -128
  187. webscout/Provider/TTS/murfai.py +0 -113
  188. webscout/Provider/TTS/parler.py +0 -111
  189. webscout/Provider/TTS/speechma.py +0 -180
  190. webscout/Provider/TTS/streamElements.py +0 -333
  191. webscout/Provider/TTS/utils.py +0 -280
  192. webscout/Provider/TeachAnything.py +0 -233
  193. webscout/Provider/TextPollinationsAI.py +0 -306
  194. webscout/Provider/TwoAI.py +0 -280
  195. webscout/Provider/TypliAI.py +0 -305
  196. webscout/Provider/Venice.py +0 -258
  197. webscout/Provider/VercelAI.py +0 -253
  198. webscout/Provider/WiseCat.py +0 -233
  199. webscout/Provider/WrDoChat.py +0 -370
  200. webscout/Provider/Writecream.py +0 -237
  201. webscout/Provider/WritingMate.py +0 -269
  202. webscout/Provider/Youchat.py +0 -330
  203. webscout/Provider/__init__.py +0 -178
  204. webscout/Provider/ai4chat.py +0 -203
  205. webscout/Provider/aimathgpt.py +0 -189
  206. webscout/Provider/akashgpt.py +0 -335
  207. webscout/Provider/asksteve.py +0 -212
  208. webscout/Provider/bagoodex.py +0 -145
  209. webscout/Provider/cerebras.py +0 -288
  210. webscout/Provider/chatglm.py +0 -215
  211. webscout/Provider/cleeai.py +0 -213
  212. webscout/Provider/copilot.py +0 -425
  213. webscout/Provider/elmo.py +0 -283
  214. webscout/Provider/freeaichat.py +0 -285
  215. webscout/Provider/geminiapi.py +0 -208
  216. webscout/Provider/geminiprorealtime.py +0 -160
  217. webscout/Provider/granite.py +0 -235
  218. webscout/Provider/hermes.py +0 -266
  219. webscout/Provider/julius.py +0 -223
  220. webscout/Provider/koala.py +0 -268
  221. webscout/Provider/learnfastai.py +0 -325
  222. webscout/Provider/llama3mitril.py +0 -215
  223. webscout/Provider/llmchat.py +0 -255
  224. webscout/Provider/llmchatco.py +0 -306
  225. webscout/Provider/meta.py +0 -798
  226. webscout/Provider/multichat.py +0 -364
  227. webscout/Provider/scira_chat.py +0 -297
  228. webscout/Provider/scnet.py +0 -243
  229. webscout/Provider/searchchat.py +0 -292
  230. webscout/Provider/sonus.py +0 -258
  231. webscout/Provider/talkai.py +0 -194
  232. webscout/Provider/toolbaz.py +0 -353
  233. webscout/Provider/turboseek.py +0 -266
  234. webscout/Provider/typefully.py +0 -330
  235. webscout/Provider/typegpt.py +0 -289
  236. webscout/Provider/uncovr.py +0 -368
  237. webscout/Provider/x0gpt.py +0 -299
  238. webscout/Provider/yep.py +0 -389
  239. webscout/litagent/__init__.py +0 -29
  240. webscout/litagent/agent.py +0 -455
  241. webscout/litagent/constants.py +0 -60
  242. webscout/litprinter/__init__.py +0 -59
  243. webscout/scout/__init__.py +0 -8
  244. webscout/scout/core/__init__.py +0 -7
  245. webscout/scout/core/crawler.py +0 -140
  246. webscout/scout/core/scout.py +0 -568
  247. webscout/scout/core/search_result.py +0 -96
  248. webscout/scout/core/text_analyzer.py +0 -63
  249. webscout/scout/core/text_utils.py +0 -277
  250. webscout/scout/core/web_analyzer.py +0 -52
  251. webscout/scout/core.py +0 -881
  252. webscout/scout/element.py +0 -460
  253. webscout/scout/parsers/__init__.py +0 -69
  254. webscout/scout/parsers/html5lib_parser.py +0 -172
  255. webscout/scout/parsers/html_parser.py +0 -236
  256. webscout/scout/parsers/lxml_parser.py +0 -178
  257. webscout/scout/utils.py +0 -37
  258. webscout/swiftcli/__init__.py +0 -95
  259. webscout/swiftcli/core/__init__.py +0 -7
  260. webscout/swiftcli/core/cli.py +0 -297
  261. webscout/swiftcli/core/context.py +0 -104
  262. webscout/swiftcli/core/group.py +0 -241
  263. webscout/swiftcli/decorators/__init__.py +0 -28
  264. webscout/swiftcli/decorators/command.py +0 -221
  265. webscout/swiftcli/decorators/options.py +0 -220
  266. webscout/swiftcli/decorators/output.py +0 -252
  267. webscout/swiftcli/exceptions.py +0 -21
  268. webscout/swiftcli/plugins/__init__.py +0 -9
  269. webscout/swiftcli/plugins/base.py +0 -135
  270. webscout/swiftcli/plugins/manager.py +0 -262
  271. webscout/swiftcli/utils/__init__.py +0 -59
  272. webscout/swiftcli/utils/formatting.py +0 -252
  273. webscout/swiftcli/utils/parsing.py +0 -267
  274. webscout/zeroart/__init__.py +0 -55
  275. webscout/zeroart/base.py +0 -60
  276. webscout/zeroart/effects.py +0 -99
  277. webscout/zeroart/fonts.py +0 -816
  278. webscout-8.2.6.dist-info/RECORD +0 -307
  279. webscout-8.2.6.dist-info/entry_points.txt +0 -3
  280. webscout-8.2.6.dist-info/top_level.txt +0 -2
  281. webstoken/__init__.py +0 -30
  282. webstoken/classifier.py +0 -189
  283. webstoken/keywords.py +0 -216
  284. webstoken/language.py +0 -128
  285. webstoken/ner.py +0 -164
  286. webstoken/normalizer.py +0 -35
  287. webstoken/processor.py +0 -77
  288. webstoken/sentiment.py +0 -206
  289. webstoken/stemmer.py +0 -73
  290. webstoken/tagger.py +0 -60
  291. webstoken/tokenizer.py +0 -158
  292. {webscout-8.2.6.dist-info → webscout-8.2.7.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))