-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebScraper-GitHub-User.py
More file actions
319 lines (263 loc) · 10.6 KB
/
Copy pathWebScraper-GitHub-User.py
File metadata and controls
319 lines (263 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/env python3
# https://github.com/VictorGabriel7Dev/webscraper-github-user
# https://victorgabriel.dev/projetos/webscraper-github-user
# SPDX-License-Identifier: AGPL-3.0-or-later
# Version: 1.01
#
# Author: Victor Gabriel
# Site: https://victorgabriel.dev
# E-mail: contato@victorgabriel.dev
# GitHub: https://github.com/VictorGabriel7Dev
# LinkedIn: https://www.linkedin.com/in/victorgabriel-dev
# WhatsApp: https://wa.me/@VictorGabriel_Dev
# Discord: @VictorGabriel.dev https://discord.com/users/1481407654458036265
# Telegram: https://t.me/VictorGabriel_Dev
# Instagram: https://www.instagram.com/VictorGabriel_Dev
# Generated by: Claude https://claude.ai
"""
webscraper-github-user
====================
A python script for Web Scrapping GitHub Users.
Scrapes a GitHub user's starred repositories and following list
directly from the GitHub HTML pages, no API token required.
Usage:
python WebScraper-GitHub-User.py <github_username>
Example:
python WebScraper-GitHub-User.py torvalds
"""
import sys
import re
import html
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
# ── ANSI colour palette ──────────────────────────────────────────────────────
class Colour:
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
CYAN = "\033[96m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
MAGENTA = "\033[95m"
RED = "\033[91m"
WHITE = "\033[97m"
GREY = "\033[90m"
# ── Helpers ──────────────────────────────────────────────────────────────────
HEADERS = {
"Host": "github.com",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8"
}
def fetch(url: str) -> str:
"""Fetch a URL and return the response body as a string."""
req = Request(url, headers=HEADERS)
try:
with urlopen(req, timeout=20) as resp:
return resp.read().decode("utf-8", errors="replace")
except HTTPError as exc:
print(
f"{Colour.RED}✗ HTTP {exc.code} while fetching:{Colour.RESET} {url}",
file=sys.stderr
)
sys.exit(1)
except URLError as exc:
print(
f"{Colour.RED}✗ Connection error:{Colour.RESET} {exc.reason}",
file=sys.stderr
)
sys.exit(1)
def banner(username: str) -> None:
w = 60
print()
print(f"{Colour.CYAN}{Colour.BOLD}{'─' * w}{Colour.RESET}")
print(
f"{Colour.CYAN}{Colour.BOLD}"
f" ⬡ webscraper-github-user"
f"{Colour.RESET}"
)
print(
f"{Colour.GREY} Target → {Colour.WHITE}{Colour.BOLD}"
f"github.com/{username}"
f"{Colour.RESET}"
)
print(f"{Colour.CYAN}{Colour.BOLD}{'─' * w}{Colour.RESET}")
print()
def section_header(title: str) -> None:
print(f"\n{Colour.YELLOW}{Colour.BOLD} ★ {title}{Colour.RESET}")
print(f"{Colour.GREY} {'·' * 50}{Colour.RESET}")
def summary(label: str, count: int) -> None:
print(
f"\n{Colour.GREEN} ✔ {label}: "
f"{Colour.BOLD}{count}{Colour.RESET}"
)
# ── Stars scraper ─────────────────────────────────────────────────────────────
def scrape_stars(username: str) -> int:
"""Yield every starred repo for *username*. Returns total count."""
section_header(f"Starred repositories: {username}")
url: str = (
f"https://github.com/{username}"
f"?direction=desc&sort=stars&tab=stars"
)
visited_pages: set[str] = set()
total = 0
while url:
if url in visited_pages:
print(
f"{Colour.GREY} ↩ Duplicate page detected, stopping.{Colour.RESET}"
)
break
visited_pages.add(url)
body = fetch(url)
lines = body.splitlines()
repo = ""
description_parts: list[str] = []
collecting_desc = False
next_url = ""
i = 0
while i < len(lines):
line = lines[i]
# Repository anchor → <a href="/user/repo">
m = re.search(r'<\s*a\s+href=["\']/([\w.\-]+/[\w.\-]+)["\']\s*>\s*$', line, re.I)
if m:
repo = m.group(1)
description_parts = []
collecting_desc = False
# Start of description paragraph
if re.search(
r'<\s*p\s+[^>]*(?:itemprop=["\']description["\']|'
r'class=["\'][^"\']*(?:d-inline-block|col-9)[^"\']*["\'])[^>]*>',
line, re.I
):
collecting_desc = True
# grab inline text on the same line
inline = re.sub(r"<[^>]+>", "", line).strip()
if inline:
description_parts.append(inline)
elif collecting_desc:
if re.search(r"<\s*/\s*p\s*>", line, re.I):
# end of description
raw = " ".join(description_parts)
desc = html.unescape(re.sub(r"<[^>]+>", "", raw)).strip(" .")
_print_star(total + 1, repo, desc or "<no description>")
total += 1
repo = ""
description_parts = []
collecting_desc = False
else:
text = re.sub(r"<[^>]+>", "", line).strip()
if text:
description_parts.append(text)
# Flush repo with empty description when metadata div appears
if (
repo
and not collecting_desc
and re.search(
r'<\s*div\s+[^>]*class=["\'][^"\']*'
r'(?:f6|color-fg-muted|mt-2)[^"\']*["\']',
line, re.I
)
):
_print_star(total + 1, repo, "<no description>")
total += 1
repo = ""
# "Next" pagination link
m_next = re.search(
r'href=["\'](https://github\.com/' + re.escape(username) +
r'\?after=[^"\']+(?:&(?:amp;)?|&)tab=stars[^"\']*)["\']'
r'[^>]*>\s*Next\s*<',
line, re.I
)
if m_next:
next_url = html.unescape(m_next.group(1))
i += 1
url = next_url # empty string → loop ends
summary("Total starred repositories", total)
return total
def _print_star(index: int, repo: str, desc: str) -> None:
idx_str = f"{Colour.GREY}{index:>4}.{Colour.RESET}"
repo_str = f"{Colour.CYAN}{Colour.BOLD}{repo}{Colour.RESET}"
desc_str = f"{Colour.DIM}{desc}{Colour.RESET}"
print(f" {idx_str} {repo_str}")
print(f" {desc_str}")
# ── Following scraper ─────────────────────────────────────────────────────────
def scrape_following(username: str) -> int:
"""Print every account that *username* follows. Returns total count."""
section_header(f"Following: {username}")
url: str = f"https://github.com/{username}?tab=following"
visited_pages: set[str] = set()
seen_users: set[str] = set()
total = 0
while url:
if url in visited_pages:
print(
f"{Colour.GREY} ↩ Duplicate page detected, stopping.{Colour.RESET}"
)
break
visited_pages.add(url)
body = fetch(url)
next_url = ""
for line in body.splitlines():
# Extract followed usernames from hovercard links
m = re.search(
r'["\']\/(?:orgs|users)\/([\w.\-]+)\/hovercard["\']',
line, re.I
)
if m:
user = m.group(1)
if user not in seen_users:
seen_users.add(user)
total += 1
_print_following(total, user)
# "Next" pagination link
m_next = re.search(
r'href=["\'](https://github\.com/' + re.escape(username) +
r'\?page=(\d+)&(?:amp;)?tab=following)["\']'
r'[^>]*>\s*Next\s*<',
line, re.I
)
if m_next:
candidate_url = html.unescape(m_next.group(1))
# Make sure "Next" is not disabled
disabled = re.search(
r'class=["\'][^"\']*(?:disabled|color-fg-muted)[^"\']*["\']'
r'[^>]*>\s*Next\s*<',
line, re.I
)
if not disabled:
next_url = candidate_url
url = next_url
summary("Total following", total)
return total
def _print_following(index: int, user: str) -> None:
idx_str = f"{Colour.GREY}{index:>4}.{Colour.RESET}"
user_str = f"{Colour.MAGENTA}{Colour.BOLD}{user}{Colour.RESET}"
url_str = f"{Colour.DIM}https://github.com/{user}{Colour.RESET}"
print(f" {idx_str} {user_str} {url_str}")
# ── Entry point ───────────────────────────────────────────────────────────────
def main() -> None:
if len(sys.argv) < 2:
print(
f"\n{Colour.RED}Usage:{Colour.RESET} "
f"python WebScraper-GitHub-User.py <github_username>\n",
file=sys.stderr
)
sys.exit(1)
username = sys.argv[1].strip().lstrip("@")
banner(username)
stars_count = scrape_stars(username)
following_count = scrape_following(username)
# ── Final summary ────────────────────────────────────────────────────────
w = 60
print(f"\n{Colour.CYAN}{Colour.BOLD}{'─' * w}{Colour.RESET}")
print(f"{Colour.BOLD} Summary for {Colour.CYAN}{username}{Colour.RESET}")
print(
f" {Colour.YELLOW}★{Colour.RESET} Stars : "
f"{Colour.BOLD}{stars_count}{Colour.RESET}"
)
print(
f" {Colour.MAGENTA}●{Colour.RESET} Following : "
f"{Colour.BOLD}{following_count}{Colour.RESET}"
)
print(f"{Colour.CYAN}{Colour.BOLD}{'─' * w}{Colour.RESET}\n")
if __name__ == "__main__":
main()