-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.py
More file actions
1446 lines (1204 loc) · 55.8 KB
/
Copy pathApp.py
File metadata and controls
1446 lines (1204 loc) · 55.8 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# assignments_app.py - Streamlit demo app for Assignment 1 & Assignment 2
import streamlit as st
import pandas as pd
import textwrap
import io, requests
st.set_page_config(page_title="Assignments Demo", layout="centered")
def show_assignment_1():
"""Assignment 1: Json to csv flattening, summarization, visualization."""
st.subheader("Assignment 1 - Json to csv flattening, Data Summarization & Visualization")
st.write("---")
st.write("**R Programming**")
st.write("Click the below button to view the R Markdown report for Assignment 1:")
st.link_button("R Markdown for Assignment 1", "https://rpubs.com/spullipu/1329879")
st.write("---")
st.write("**Python Programming**")
code_a1 = """
#!/usr/bin/env python3
'''
# Assignment 1 - JSON → CSV pipeline with enrichment & parallelism
# ---------------------------------------------------------------
# • Flatten each infringing URL to its own row
# • Add 'domain' and 'ip_address' columns
# • Parallelise IP-look-ups with ≥ 4 CPUs
# • Produce three summary tables
# Author: Siva Mani Subrahmanya Hari Vamsi
# Date : 15-07-2025
'''
import json
import csv
import socket
from pathlib import Path
from urllib.parse import urlparse
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import Counter
import pandas as pd
import re, requests
# -------- CONFIG -------------------------------------------------------------
# Google Drive share-link → file-ID → direct-download URL
DRIVE_FILE_ID = "134U6xLIZUZ9sA1BW-X9TLZtUlEYCvQwz"
INPUT_JSON = ( # we now pass a URL, not a Path
f"https://drive.google.com/uc?export=download&id={DRIVE_FILE_ID}"
)
OUTPUT_CSV = Path("flattened_infringing_urls.csv")
N_WORKERS = 8
TIMEOUT_S = 3
# -----------------------------------------------------------------------------
def load_json(src: str | Path) -> dict:
'''
Load a JSON document from either
• a local file (Path / str) - existing behaviour, or
• an http/https URL - used for the public Google Drive link.
'''
src_str = str(src)
#1️⃣ Remote file ----------------------------------------------------------
if src_str.startswith(("http://", "https://")):
# Google Drive ‘share’ links need converting to the *download* endpoint
m = re.search(r"/d/([^/]+)/", src_str)
if m:
file_id = m.group(1)
src_str = f"https://drive.google.com/uc?export=download&id={file_id}"
# small files (<100 MB) download in one go; large files may need a second
with requests.Session() as sess:
r = sess.get(src_str, timeout=30, stream=True)
# If we hit Drive’s virus-scan / confirm page, grab the token & resend
if "content-disposition" not in r.headers:
for k, v in r.cookies.items():
if k.startswith("download_warning"):
r = sess.get(src_str, params={"confirm": v}, timeout=30)
break
r.raise_for_status()
return r.json()
#2️⃣ Local file -----------------------------------------------------------
with Path(src_str).open("r", encoding="utf-8") as f:
return json.load(f)
def flatten_notices(raw: dict) -> list[dict]:
'''
Flatten the nested JSON structure so each infringing URL gets its own
dictionary (future CSV row). Extracts relevant fields from each notice.
'''
rows = []
for notice in raw.get("notices", []):
base = {
"notice_id": notice.get("id"),
"title": notice.get("title"),
"sender": notice.get("sender_name"),
"principal": notice.get("principal_name"),
"recipient": notice.get("recipient_name"),
"date_sent": notice.get("date_sent"),
}
for work in notice.get("works", []):
description = work.get("description")
for item in work.get("infringing_urls", []):
url = item.get("url")
rows.append(
{
**base,
"description": description,
"infringing_url": url,
"domain": urlparse(url).netloc.lower(), # Extract domain from URL
}
)
return rows
def resolve_ip(domain: str) -> str:
'''
Return the IPv4 address for a domain.
Returns 'N/A' if the lookup fails (e.g., DNS error or timeout).
'''
try:
socket.setdefaulttimeout(TIMEOUT_S)
return socket.gethostbyname(domain)
except OSError:
return "N/A"
def enrich_with_ip(rows: list[dict]) -> None:
'''
Perform parallel DNS look-ups using a thread pool.
Adds an 'ip_address' key to each row in-place.
Caches results so each domain is only looked up once.
'''
unique_domains = {row["domain"] for row in rows}
ip_cache: dict[str, str] = {}
# Submit DNS lookups in parallel
with ThreadPoolExecutor(max_workers=N_WORKERS) as pool:
future_to_domain = {pool.submit(resolve_ip, d): d for d in unique_domains}
for future in as_completed(future_to_domain):
dom = future_to_domain[future]
ip_cache[dom] = future.result()
# Assign resolved IPs back to each row
for row in rows:
row["ip_address"] = ip_cache[row["domain"]]
def write_csv(rows: list[dict], out_path: Path) -> None:
'''
Write the list of dictionaries to a CSV file.
Raises an error if there is no data.
'''
if not rows:
raise ValueError("No data extracted - check input file.")
fields = list(rows[0].keys())
with out_path.open("w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
w.writerows(rows)
def summarise(rows: list[dict]) -> None:
'''
Print three summary tables:
- Top 5 Principals
- Top 5 Infringing Domains
- Top 5 Recipients
'''
principals = Counter(r["principal"] for r in rows).most_common(5)
domains = Counter(r["domain"] for r in rows).most_common(5)
recipients = Counter(r["recipient"] for r in rows).most_common(5)
print("\nTop 5 Principals:")
for p, n in principals:
print(f" {p:<30} {n:>6}")
print("\nTop 5 Infringing Domains:")
for d, n in domains:
print(f" {d:<30} {n:>6}")
print("\nTop 5 Recipients:")
for r, n in recipients:
print(f" {r:<30} {n:>6}")
def main() -> None:
'''
Main pipeline:
- Load JSON data
- Flatten notices to rows
- Enrich with IP addresses (parallel DNS)
- Clean/standardize principal and domain names
- Print summary insights
- Write output CSV
'''
raw = load_json(INPUT_JSON)
rows = flatten_notices(raw)
enrich_with_ip(rows)
df = pd.DataFrame(rows)
def tidy_principal(name: str) -> str:
'''
Standardize principal names: lowercase, remove punctuation,
remove 'inc', collapse whitespace, and title-case.
'''
if pd.isna(name):
return "Unknown"
n = name.lower()
n = re.sub(r'[,.\']', '', n) # remove punctuation
n = n.replace(' inc', '').strip()
n = re.sub(r'\s+', ' ', n)
return n.title()
df["principal_clean"] = df["principal"].apply(tidy_principal)
def root_domain(d: str) -> str:
'''
Extract the root domain (last two labels) and remove 'www.' prefix.
'''
if pd.isna(d):
return "unknown"
d = d.lower()
d = re.sub(r'^www\d*\.', '', d) # drop www., www2. etc.
return '.'.join(d.split('.')[-2:]) # keep last two labels
df["root_domain"] = df["domain"].apply(root_domain)
print("\n🔸 Top Principals (cleaned):")
print(df["principal_clean"].value_counts().head(10))
print("\n🔸 Top Root Domains:")
print(df["root_domain"].value_counts().head(10))
# 2a. Notice volume over time (monthly trend)
df["month"] = pd.to_datetime(df["date_sent"], utc=True).dt.tz_localize(None).dt.to_period("M")
trend = df.groupby("month").size()
print("\n🔸 Monthly notice volume (last 12):")
print(trend.tail(12))
# 2b. IP addresses hosting many distinct domains
ip_hosting = (df.groupby("ip_address")["root_domain"]
.nunique()
.sort_values(ascending=False)
.head(10))
ip_hosting = ip_hosting[ip_hosting.index != "N/A"]
print("\n🔸 IPs hosting the most *unique* infringing domains:")
print(ip_hosting)
# Write the enriched and flattened data to CSV
write_csv(rows, OUTPUT_CSV)
print(f"\n✅ CSV written to: {OUTPUT_CSV.resolve()}")
if __name__ == "__main__":
main()
"""
with st.expander("⬇️ Show Python code"):
st.code(code_a1, language="python")
# ---------- execute the code ----------
import json
import csv
import socket
from pathlib import Path
from urllib.parse import urlparse
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import Counter
import pandas as pd
import re, requests
# -------- CONFIG -------------------------------------------------------------
# Google Drive share-link → file-ID → direct-download URL
DRIVE_FILE_ID = "134U6xLIZUZ9sA1BW-X9TLZtUlEYCvQwz"
INPUT_JSON = ( # we now pass a URL, not a Path
f"https://drive.google.com/uc?export=download&id={DRIVE_FILE_ID}"
)
OUTPUT_CSV = Path("flattened_infringing_urls.csv")
N_WORKERS = 8
TIMEOUT_S = 3
# -----------------------------------------------------------------------------
def load_json(src: str | Path) -> dict:
'''
Load a JSON document from either
• a local file (Path / str) - existing behaviour, or
• an http/https URL - used for the public Google Drive link.
'''
src_str = str(src)
# 1️⃣ Remote file ----------------------------------------------------------
if src_str.startswith(("http://", "https://")):
# Google Drive ‘share’ links need converting to the *download* endpoint
m = re.search(r"/d/([^/]+)/", src_str)
if m:
file_id = m.group(1)
src_str = f"https://drive.google.com/uc?export=download&id={file_id}"
# small files (<100 MB) download in one go; large files may need a second
with requests.Session() as sess:
r = sess.get(src_str, timeout=30, stream=True)
# If we hit Drive’s virus-scan / confirm page, grab the token & resend
if "content-disposition" not in r.headers:
for k, v in r.cookies.items():
if k.startswith("download_warning"):
r = sess.get(src_str, params={"confirm": v}, timeout=30)
break
r.raise_for_status()
return r.json()
# 2️⃣ Local file -----------------------------------------------------------
with Path(src_str).open("r", encoding="utf-8") as f:
return json.load(f)
def flatten_notices(raw: dict) -> list[dict]:
'''
Flatten the nested JSON structure so each infringing URL gets its own
dictionary (future CSV row). Extracts relevant fields from each notice.
'''
rows = []
for notice in raw.get("notices", []):
base = {
"notice_id": notice.get("id"),
"title": notice.get("title"),
"sender": notice.get("sender_name"),
"principal": notice.get("principal_name"),
"recipient": notice.get("recipient_name"),
"date_sent": notice.get("date_sent"),
}
for work in notice.get("works", []):
description = work.get("description")
for item in work.get("infringing_urls", []):
url = item.get("url")
rows.append(
{
**base,
"description": description,
"infringing_url": url,
"domain": urlparse(url).netloc.lower(), # Extract domain from URL
}
)
return rows
def resolve_ip(domain: str) -> str:
'''
Return the IPv4 address for a domain.
Returns 'N/A' if the lookup fails (e.g., DNS error or timeout).
'''
try:
socket.setdefaulttimeout(TIMEOUT_S)
return socket.gethostbyname(domain)
except OSError:
return "N/A"
def enrich_with_ip(rows: list[dict]) -> None:
'''
Perform parallel DNS look-ups using a thread pool.
Adds an 'ip_address' key to each row in-place.
Caches results so each domain is only looked up once.
'''
unique_domains = {row["domain"] for row in rows}
ip_cache: dict[str, str] = {}
# Submit DNS lookups in parallel
with ThreadPoolExecutor(max_workers=N_WORKERS) as pool:
future_to_domain = {pool.submit(resolve_ip, d): d for d in unique_domains}
for future in as_completed(future_to_domain):
dom = future_to_domain[future]
ip_cache[dom] = future.result()
# Assign resolved IPs back to each row
for row in rows:
row["ip_address"] = ip_cache[row["domain"]]
def write_csv(rows: list[dict], out_path: Path) -> None:
'''
Write the list of dictionaries to a CSV file.
Raises an error if there is no data.
'''
if not rows:
raise ValueError("No data extracted – check input file.")
fields = list(rows[0].keys())
with out_path.open("w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
w.writerows(rows)
def summarise(rows: list[dict]) -> None:
'''
st.write three summary tables:
- Top 5 Principals
- Top 5 Infringing Domains
- Top 5 Recipients
'''
principals = Counter(r["principal"] for r in rows).most_common(5)
domains = Counter(r["domain"] for r in rows).most_common(5)
recipients = Counter(r["recipient"] for r in rows).most_common(5)
st.write("\nTop 5 Principals:")
for p, n in principals:
st.write(f" {p:<30} {n:>6}")
st.write("\nTop 5 Infringing Domains:")
for d, n in domains:
st.write(f" {d:<30} {n:>6}")
st.write("\nTop 5 Recipients:")
for r, n in recipients:
st.write(f" {r:<30} {n:>6}")
def main() -> None:
'''
Main pipeline:
- Load JSON data
- Flatten notices to rows
- Enrich with IP addresses (parallel DNS)
- Clean/standardize principal and domain names
- st.ite summary insights
- Write output CSV
'''
raw = load_json(INPUT_JSON)
rows = flatten_notices(raw)
enrich_with_ip(rows)
df = pd.DataFrame(rows)
def tidy_principal(name: str) -> str:
'''
Standardize principal names: lowercase, remove punctuation,
remove 'inc', collapse whitespace, and title-case.
'''
if pd.isna(name):
return "Unknown"
n = name.lower()
n = re.sub(r'[,.\']', '', n) # remove punctuation
n = n.replace(' inc', '').strip()
n = re.sub(r'\s+', ' ', n)
return n.title()
df["principal_clean"] = df["principal"].apply(tidy_principal)
def root_domain(d: str) -> str:
'''
Extract the root domain (last two labels) and remove 'www.' prefix.
'''
if pd.isna(d):
return "unknown"
d = d.lower()
d = re.sub(r'^www\d*\.', '', d) # drop www., www2. etc.
return '.'.join(d.split('.')[-2:]) # keep last two labels
df["root_domain"] = df["domain"].apply(root_domain)
df_final = pd.DataFrame(rows) # turn list-of-dicts into a DataFrame
st.subheader("Csv File Preview")
st.dataframe(df_final.head(), use_container_width=True)
csv_bytes = df_final.to_csv(index=False).encode("utf-8")
st.download_button(
label="⬇️ Download CSV",
data=csv_bytes,
file_name="flattened_infringing_urls.csv",
mime="text/csv",
)
st.write("\n🔸 Top Root Domains:")
st.write(df["root_domain"].value_counts().head(10))
st.bar_chart(df["root_domain"].value_counts().head(10), x_label="Domain Name", y_label="Count")
# IP addresses hosting many distinct domains
ip_hosting = (df.groupby("ip_address")["root_domain"]
.nunique()
.sort_values(ascending=False)
.head(10))
ip_hosting = ip_hosting[ip_hosting.index != "N/A"]
st.write("\n🔸 IPs hosting the most *unique* infringing domains:")
st.write(ip_hosting)
st.bar_chart(ip_hosting, x_label="Unique Domains Hosted", y_label="IP Address",horizontal=True)
st.write("\n🔸 Top Principals (cleaned):")
st.write(df["principal_clean"].value_counts().head(10))
# Write the enriched and flattened data to CSV
write_csv(rows, OUTPUT_CSV)
st.write("Summarizations")
if __name__ == "__main__":
main()
def show_assignment_2():
"""Render Assignment 2 with selectable approaches."""
st.subheader("Assignment 2 - Web Scraping & Data Extraction")
st.write("---")
st.write("**R Programming**")
st.write("Click the below button to view the R Markdown report for Assignment 2:")
st.link_button("R Markdown for Assignment 2", "https://rpubs.com/spullipu/1329862")
st.write("---")
st.write("**Python Programming**")
approach = st.radio("Select an approach:", ("Approach 1 - Manual", "Approach 2 - Selenium"))
st.write("The Web Page to scrape is: https://journals.sagepub.com/toc/JMX/current")
if approach.startswith("Approach 1"):
_show_approach_1()
else:
_show_approach_2()
def _show_approach_1():
"""Manual web scraping using downloaded html in Google Drive"""
st.write("**Approach 1** - Manual web scraping using downloaded html file in Google Drive")
code_rf = """
import csv, re, os ,requests
from urllib.parse import urlparse, parse_qs
from bs4 import BeautifulSoup
def _find_first_publish_date(elem) -> str:
#Look anywhere inside *elem* for text like First published online November 16, 2024' or 'First Published January 3 2025'
text = elem.get_text(" ", strip=True)
# Search for common publish date patterns in the text
m = re.search(
r'First\s+published(?:\s+online)?\s+([A-Za-z]+\s+\d{1,2},?\s+\d{4})',
text, re.I
)
return m.group(1) if m else ''
def _clean_abstract(raw: str) -> str:
# Remove site-specific clutter such as 'Show abstract', 'Hide abstract', 'Preview abstract', and a leading 'Abstract:' label.
# 1) Remove show/hide/preview toggles from abstract text
txt = re.sub(r'\b(?:Show|Hide|Preview|Full)\s*abstract\b', '', raw, flags=re.I)
# 2) Remove a leading 'Abstract:' label (sometimes repeated)
txt = re.sub(r'^\s*Abstract\s*:?\s*', '', txt, flags=re.I)
# 3) Collapse extra whitespace
return re.sub(r'\s+', ' ', txt).strip()
def _canonical_doi(href: str) -> str:
# Return 'https://doi.org/<doi>' if a DOI pattern is present,otherwise return the original href.
m = re.search(r'(10\.\d{4,9}/[^\s/#?]+)', href) # DOI core pattern
return f"https://doi.org/{m.group(1)}" if m else href
def extract_article_data(container):
# Extract article data from a container element.
article_data = {
'title': '',
'authors': '',
'date': '',
'doi': '',
'abstract': ''
}
# ----- title ------------------------------------------
# Try multiple selectors to find the article title
for selector in [
'h3.item-title','h4.item-title','h5.item-title','div.art_title',
'div.hlFld-Title','a.ref.nowrap','.tocHeading',
'h3','h4','h5','h2','[class*="title"]'
]:
title_elem = container.select_one(selector)
if title_elem:
raw = title_elem.get_text(" ", strip=True).replace("\xa0", " ")
article_data['title'] = re.sub(r'\s+', ' ', raw).strip()
break
# ----- authors -----
# Try multiple selectors to find the authors
for selector in [
'div.contrib','div.contributors','div.author','div.authors',
'span.hlFld-ContribAuthor','div.art_authors',
'[class*="contrib"]','[class*="author"]'
]:
authors_elem = container.select_one(selector)
if authors_elem:
# Separate child nodes with ", " and normalize whitespace
authors_txt = authors_elem.get_text(", ", strip=True)
article_data['authors'] = re.sub(r'\s+', ' ', authors_txt).strip(" ,")
break
# ----- date ➊: try quick CSS selectors first -----
# Try to find the publication date using common selectors
for selector in [
'div.pub-date','div.published-date','span.pub-date',
'div.date','[class*="date"]','[class*="publish"]'
]:
date_elem = container.select_one(selector)
if date_elem and date_elem.get_text(strip=True):
article_data['date'] = date_elem.get_text(strip=True)
break
# ----- date ➋: fallback - scan for “First published online …” -----
# If no date found, look for a "First published" pattern in the text
if not article_data['date']:
article_data['date'] = _find_first_publish_date(container)
# ---------- DOI ----------
# Try to find a DOI link in the container
doi = ''
doi_elem = container.find('a', href=re.compile(r'doi\.org|/doi/'))
if doi_elem:
doi = _canonical_doi(doi_elem.get('href', ''))
article_data['doi'] = doi
# ---------- ABSTRACT ----------
# Try multiple selectors to find the abstract
abstract = ''
for selector in [
'div.abstract' , 'div.abstractSection' , 'div.hlFld-Abstract',
'p.abstract' , '[class*="abstract"]'
]:
elem = container.select_one(selector)
if elem:
abstract = _clean_abstract(elem.get_text(" ", strip=True))
if abstract: # non-empty after cleaning
break
article_data['abstract'] = abstract
return article_data
def extract_articles_from_soup(soup):
#Extract articles from BeautifulSoup object with comprehensive selectors
articles = []
# SAGE journal specific selectors for article containers
article_selectors = [
'div.issue-item',
'div.issue-item-container',
'div.article-list-item',
'article.item',
'div.hlFld-Fulltext',
'div.tocHeading',
'div.art_title',
'div[class*="issue-item"]',
'div[class*="article"]',
'li.item',
'div.item'
]
article_containers = []
# Try each selector until articles are found
for selector in article_selectors:
containers = soup.select(selector)
if containers:
article_containers = containers
print(f"Found {len(containers)} articles using selector: {selector}")
break
# If no containers found, try broader search for potential article containers
if not article_containers:
# Look for any element that might contain article info
potential_containers = soup.find_all(['div', 'article', 'li'],
string=re.compile(r'doi|author|abstract|volume|issue', re.I))
article_containers = potential_containers[:20] # Limit to avoid too many false positives
# Extract data from each article container
for container in article_containers:
article_data = extract_article_data(container)
if article_data['title']: # Only add if we have a title
articles.append(article_data)
return articles
def process_manual_html(html_file_path):
# Process manually saved HTML file from the journal page
try:
with open(html_file_path, 'r', encoding='utf-8') as f:
html_content = f.read()
soup = BeautifulSoup(html_content, 'html.parser')
return extract_articles_from_soup(soup)
except Exception as e:
print(f"Error processing manual HTML file: {e}")
return []
def save_to_csv(articles, filename='journal_articles.csv'):
# Save articles to CSV file
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
fieldnames = ['title', 'authors', 'date', 'doi', 'abstract']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for article in articles:
writer.writerow(article)
print(f"Saved {len(articles)} articles to {filename}")
def _google_drive_id(url: str) -> str:
# Extract the file-ID from any Google-Drive share link.
# 1) pattern “.../d/<ID>/view”
m = re.search(r'/d/([0-9A-Za-z_-]{10,})', url)
if m:
return m.group(1)
# 2) fallback — check ?id=<ID>
qs = parse_qs(urlparse(url).query)
return qs.get('id', [''])[0] # returns '' if 'id' not present
def fetch_html_from_gdrive(url: str) -> str:
# Download the *raw* file content from a public Google-Drive link. Returns HTML text.
file_id = _google_drive_id(url)
if not file_id:
raise ValueError("❌ Couldn't find a file ID in the provided link.")
# direct-download endpoint
dl_url = f"https://drive.google.com/uc?export=download&id={file_id}"
resp = requests.get(dl_url, headers={'User-Agent': 'Mozilla/5.0'})
resp.raise_for_status() # 4xx / 5xx -> exception
return resp.text # HTML string
def main():
# Main function to orchestrate the scraping and saving process. Looks for HTML file in the Google Drive, extracts articles, and saves them to CSV.
print("=" * 60)
print("GOOGLE-DRIVE JOURNAL ARTICLE SCRAPER")
print("=" * 60)
gdrive_url = (
"https://drive.google.com/file/d/1At1Y8CbwlInSQC5fbMvyExklEEKvctli/view?usp=sharing"
)
try:
print("Downloading HTML from Google Drive …")
html_content = fetch_html_from_gdrive(gdrive_url)
soup = BeautifulSoup(html_content, 'html.parser')
articles = extract_articles_from_soup(soup)
if not articles:
print("❌ No articles found — did the HTML structure change?")
return
print("\nArticle Summary:")
print("-" * 60)
for i, article in enumerate(articles, 1):
print(f"{i}. {article['title']}")
print(f" Authors: {article['authors']}")
print(f" Date: {article['date']}")
print(f" DOI: {article['doi']}")
abstract_preview = article['abstract'][:150] + "..." if len(article['abstract']) > 150 else article['abstract']
print(f" Abstract: {abstract_preview}")
print()
print(f"✓ SUCCESS: scraped {len(articles)} articles")
save_to_csv(articles)
except Exception as exc:
print(f"Download / parse error: {exc}")
if __name__ == "__main__":
main()
"""
with st.expander("⬇️ Show Python code"):
st.code(code_rf, language="python")
import csv, re, os ,requests
from urllib.parse import urlparse, parse_qs
from bs4 import BeautifulSoup
def _find_first_publish_date(elem) -> str:
#Look anywhere inside *elem* for text like First published online November 16, 2024' or 'First Published January 3 2025'
text = elem.get_text(" ", strip=True)
# Search for common publish date patterns in the text
m = re.search(
r'First\s+published(?:\s+online)?\s+([A-Za-z]+\s+\d{1,2},?\s+\d{4})',
text, re.I
)
return m.group(1) if m else ''
def _clean_abstract(raw: str) -> str:
# Remove site-specific clutter such as 'Show abstract', 'Hide abstract', 'Preview abstract', and a leading 'Abstract:' label.
# 1) Remove show/hide/preview toggles from abstract text
txt = re.sub(r'\b(?:Show|Hide|Preview|Full)\s*abstract\b', '', raw, flags=re.I)
# 2) Remove a leading 'Abstract:' label (sometimes repeated)
txt = re.sub(r'^\s*Abstract\s*:?\s*', '', txt, flags=re.I)
# 3) Collapse extra whitespace
return re.sub(r'\s+', ' ', txt).strip()
def _canonical_doi(href: str) -> str:
# Return 'https://doi.org/<doi>' if a DOI pattern is present,otherwise return the original href.
m = re.search(r'(10\.\d{4,9}/[^\s/#?]+)', href) # DOI core pattern
return f"https://doi.org/{m.group(1)}" if m else href
def extract_article_data(container):
# Extract article data from a container element.
article_data = {
'title': '',
'authors': '',
'date': '',
'doi': '',
'abstract': ''
}
# ----- title ------------------------------------------
# Try multiple selectors to find the article title
for selector in [
'h3.item-title','h4.item-title','h5.item-title','div.art_title',
'div.hlFld-Title','a.ref.nowrap','.tocHeading',
'h3','h4','h5','h2','[class*="title"]'
]:
title_elem = container.select_one(selector)
if title_elem:
raw = title_elem.get_text(" ", strip=True).replace("\xa0", " ")
article_data['title'] = re.sub(r'\s+', ' ', raw).strip()
break
# ----- authors -----
# Try multiple selectors to find the authors
for selector in [
'div.contrib','div.contributors','div.author','div.authors',
'span.hlFld-ContribAuthor','div.art_authors',
'[class*="contrib"]','[class*="author"]'
]:
authors_elem = container.select_one(selector)
if authors_elem:
# Separate child nodes with ", " and normalize whitespace
authors_txt = authors_elem.get_text(", ", strip=True)
article_data['authors'] = re.sub(r'\s+', ' ', authors_txt).strip(" ,")
break
# ----- date ➊: try quick CSS selectors first -----
# Try to find the publication date using common selectors
for selector in [
'div.pub-date','div.published-date','span.pub-date',
'div.date','[class*="date"]','[class*="publish"]'
]:
date_elem = container.select_one(selector)
if date_elem and date_elem.get_text(strip=True):
article_data['date'] = date_elem.get_text(strip=True)
break
# ----- date ➋: fallback - scan for “First published online …” -----
# If no date found, look for a "First published" pattern in the text
if not article_data['date']:
article_data['date'] = _find_first_publish_date(container)
# ---------- DOI ----------
# Try to find a DOI link in the container
doi = ''
doi_elem = container.find('a', href=re.compile(r'doi\.org|/doi/'))
if doi_elem:
doi = _canonical_doi(doi_elem.get('href', ''))
article_data['doi'] = doi
# ---------- ABSTRACT ----------
# Try multiple selectors to find the abstract
abstract = ''
for selector in [
'div.abstract' , 'div.abstractSection' , 'div.hlFld-Abstract',
'p.abstract' , '[class*="abstract"]'
]:
elem = container.select_one(selector)
if elem:
abstract = _clean_abstract(elem.get_text(" ", strip=True))
if abstract: # non-empty after cleaning
break
article_data['abstract'] = abstract
return article_data
def extract_articles_from_soup(soup):
#Extract articles from BeautifulSoup object with comprehensive selectors
articles = []
# SAGE journal specific selectors for article containers
article_selectors = [
'div.issue-item',
'div.issue-item-container',
'div.article-list-item',
'article.item',
'div.hlFld-Fulltext',
'div.tocHeading',
'div.art_title',
'div[class*="issue-item"]',
'div[class*="article"]',
'li.item',
'div.item'
]
article_containers = []
# Try each selector until articles are found
for selector in article_selectors:
containers = soup.select(selector)
if containers:
article_containers = containers
st.write(f"Found {len(containers)} articles using selector: {selector}")
break
# If no containers found, try broader search for potential article containers
if not article_containers:
# Look for any element that might contain article info
potential_containers = soup.find_all(['div', 'article', 'li'],
string=re.compile(r'doi|author|abstract|volume|issue', re.I))
article_containers = potential_containers[:20] # Limit to avoid too many false positives
# Extract data from each article container
for container in article_containers:
article_data = extract_article_data(container)
if article_data['title']: # Only add if we have a title
articles.append(article_data)
return articles
def process_manual_html(html_file_path):
# Process manually saved HTML file from the journal page
try:
with open(html_file_path, 'r', encoding='utf-8') as f:
html_content = f.read()
soup = BeautifulSoup(html_content, 'html.parser')
return extract_articles_from_soup(soup)
except Exception as e:
st.write(f"Error processing manual HTML file: {e}")
return []
def save_to_csv(articles, filename='journal_articles.csv'):
# Save articles to CSV file
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
fieldnames = ['title', 'authors', 'date', 'doi', 'abstract']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for article in articles:
writer.writerow(article)
st.write(f"Saved {len(articles)} articles to {filename}")
def _google_drive_id(url: str) -> str:
# Extract the file-ID from any Google-Drive share link.
# 1) pattern “.../d/<ID>/view”
m = re.search(r'/d/([0-9A-Za-z_-]{10,})', url)
if m:
return m.group(1)
# 2) fallback — check ?id=<ID>
qs = parse_qs(urlparse(url).query)
return qs.get('id', [''])[0] # returns '' if 'id' not present
def fetch_html_from_gdrive(url: str) -> str:
# Download the *raw* file content from a public Google-Drive link. Returns HTML text.
file_id = _google_drive_id(url)
if not file_id:
raise ValueError("❌ Couldn't find a file ID in the provided link.")
# direct-download endpoint
dl_url = f"https://drive.google.com/uc?export=download&id={file_id}"
resp = requests.get(dl_url, headers={'User-Agent': 'Mozilla/5.0'})
resp.raise_for_status() # 4xx / 5xx -> exception
return resp.text # HTML string
def main():
# Main function to orchestrate the scraping and saving process. Looks for HTML file in the Google Drive, extracts articles, and saves them to CSV.
st.write("=" * 60)
st.write("GOOGLE-DRIVE JOURNAL ARTICLE SCRAPER")
st.write("=" * 60)
gdrive_url = (
"https://drive.google.com/file/d/1At1Y8CbwlInSQC5fbMvyExklEEKvctli/view?usp=sharing"
)
try:
st.write("Downloading HTML from Google Drive …")
html_content = fetch_html_from_gdrive(gdrive_url)
soup = BeautifulSoup(html_content, 'html.parser')
articles = extract_articles_from_soup(soup)
if not articles:
st.write("❌ No articles found — did the HTML structure change?")
return
st.write("\nArticle Summary:")
st.write("-" * 60)
for i, article in enumerate(articles, 1):
st.write(f"{i}. {article['title']}")
st.write(f" Authors: {article['authors']}")
st.write(f" Date: {article['date']}")
st.write(f" DOI: {article['doi']}")
abstract_preview = article['abstract'][:150] + "..." if len(article['abstract']) > 150 else article['abstract']
st.write(f" Abstract: {abstract_preview}")
st.write()