-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsitescrape.py
1224 lines (1224 loc) · 39.9 KB
/
sitescrape.py
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
#!/usr/local/bin/python3.12
#
# JournalList.net website scraper to scan all sites in a list and find all social, contact, and vendor links.
#
# usage: sitescrape.py [-h] [-v] [-s] [-r] [-j] [-c URL] [-d DIRNAME] [-w WEBCRAWL] url_or_filenam
#
# Scrapes websites to discover: 'name', 'contact', 'social', and 'copyright' and writes trust.txt file. Optionally, checks webcrawler ouptut for additional 'belongto' entries.
#
# positional arguments:
# url_or_filename url to scrape or name of a .csv file containing a list of urls to scape
#
# options:
# -h, --help show this help message and exit
# -v, --verbose increase output verbosity
# -s, --save save HTML from the website
# -r, --redo redo generation of trust.txt files from HTML previously saved with -s option
# -j, --forcejl force belongto=https://www.journallist.net/
# -c URL, --url URL force controlledby=URL
# -b URL, --url URL force belongto=URL
# -d DIRNAME,--dirname DIRNAME
# name of directory to write output, defualt to current directory
# -w WEBCRAWL, --webcrawl WEBCRAWL
# name of webcrawler output directory to check for belongto entries
#
# Copyright (c) 2021 Brown Wolf Consulting LLC
# License: Creative Commons Attribution-NonCommercial-ShareAlike license. See: https://creativecommons.org/
#
#--------------------------------------------------------------------------------------------------
import sys
import os
import requests
import re
import html
from bs4 import BeautifulSoup
import argparse
from html.parser import HTMLParser
from urllib.parse import unquote
from urllib.parse import urlparse
#
# Define global variables
#
# Define set of error text to check in returned HTML text
#
errors = [
"Access denied",
"Domain Not Valid",
"Drupal",
"ErrorPageController",
"Index of",
"OH SNAP!",
"Page Not Found",
"Private Site",
"Server Error",
"Site Not Found",
"This is the default server vhost",
"Under Construction",
"Untitled Page",
"Welcome to nginx!"
]
#
# Define list of domain registrars to check for expired domains
#
registrars = [
"www.123-reg.co.uk",
"www.bluehost.com",
"www.domain.com",
"www.dynadot.com",
"www.enom.com",
"www.godaddy.com",
"www.hugedomains.com",
"www.name.com",
"www.namecheap.com",
"www.namesilo.com"
]
#
# Define list of known vendors, add to this list to add new vendors
#
vendors = [
"887media.com",
"bloxdigital.com",
"bulletlink.com",
"creativecirclemedia.com",
"creativecirclemedia.com",
"crowct.com",
"dirxion.com",
"disqus.com",
"etypeservices.com",
"etypeservices.net",
"going1up.com",
"intertechmedia.com",
"locablepublishernetwork.com",
"metropublisher.com",
"our-hometown.com",
"publishwithfoundation.com",
"socastdigital.com",
"surfnewmedia.com",
"tecnavia.com",
"townnews.com",
"websitesfornewspapers.com",
"xyzscripts.com"
]
#
# Define media conglomerates that publish multiple brands on different domains, add to this list to add new media conglomerates
#
chains = {
"Advance Local Media":"https://www.advancelocal.com/",
"Allen Media Broadcasting":"https://allenmediabroadcasting.com/",
"Alpha Media":"https://www.alphamediausa.com/",
"Annex Business Media":"https://www.annexbusinessmedia.com/",
"C&S Media":"https://csmediatexas.com/",
"CherryRoad Media":"https://cherryroad-media.com/",
"Colorado Community Media":"https://coloradocommunitymedia.com/",
"Cumulus Media":"https://www.cumulusmedia.com/",
"Dow Jones & Company":"https://www.dowjones.com/",
"Ellington":"http://www.connectionnewspapers.com/",
"Gannett":"https://www.gannett.com/",
"Gray Television":"https://www.gray.tv/",
"Hearst":"https://www.hearst.com/",
"Independent Newsmedia":"https://newszap.com/",
"Lee Enterprises":"https://lee.net/",
"Mansueto":"https://www.mansueto.com/",
"MediaNews Group":"https://www.medianewsgroup.com/",
"Mountain Media":"https://mountainmedianews.com/",
"News Media Corporation":"http://www.newsmediacorporation.com/",
"Outdoor Sportsman Group":"https://www.outdoorsg.com/",
"Penske Media Corporation":"https://pmc.com/",
"Postmedia Network":"https://www.postmedia.com/",
"Scripps Media":"https://scripps.com/",
"Sinclair Broadcast Group":"https://sbgi.net/",
"Swift Communications":"https://www.swiftcom.com/",
"Trusted Media Brands":"https://www.trustedmediabrands.com/",
"Vox Media":"https://corp.voxmedia.com/"
}
#
# Define list of social networks, add to this list to add new social networks
#
socials = [
"facebook.com",
"lipboard.com",
"instagram.com",
"linkedin.com",
"newsbreak.com",
"pinterest.com",
"post.news",
"threads.net",
"twitter.com",
"weibo.com",
"x.com",
"youtube.com"
]
#
# Define url exceptions, primarily to catch social network references that aren't the actual handle for the organization
#
exceptions = [
"//staticxx.facebook.com",
"//staticxx.facebook.com/",
"http://facebook.com",
"https://facebook.com",
"http://www.facebook.com",
"https://www.facebook.com",
"//facebook.com",
"//www.facebook.com",
"//graph.facebook.com",
"facebook.com/profile.ph",
"http://instagram.com",
"https://instagram.com",
"http://www.instagram.com",
"https://www.instagram.com",
"//instagram.com",
"//platform.instagram.com",
"http://twitter.com",
"https://twitter.com",
"http://www.twitter.com",
"https://www.twitter.com",
"//twitter.com",
"//platform.twitter.com",
"//syndication.twitter.com",
"//youtube.com",
"http://linkedin.com",
"https://linkedin.com",
"http://www.linkedin.com",
"https://www.linkedin.com",
"//linkedin.com",
"//platform.linkedin.com",
"http://pinterest.com",
"https://pinterest.com",
"http://www.pinterest.com",
"https://www.pinterest.com",
"https://www.pinterest.com/",
"https://www.pinterest.com/pin/create/button/",
"//pinterest.com",
"//assets.pinterest.com",
"//api.pinterest.com"
]
#
# Define embedded exceptions
#
embedded = [
"/wp-content",
"share",
"/intent",
"appId",
"/pin/create/",
"/media/set",
"youtube.com/watch",
"/favicon.",
"//static.xx.fbcdn.net/",
"squarespace.com/",
"BOOMR.url",
"-contact-",
"-about-",
"abouts",
"-connect",
"contact-form",
"addtoany.com"
]
#
# Define home page variants (ignoring case) for removal from site name
#
homepage = ["home page [-|\\|]", "home page$", "homepage [-|\\|]", "homepage$", "home [-|\\|]", "[-|\\|] home$"]
#
# Define various forms of "contact" in contact urls
#
contactlist = ["contact-us", "about-us", "contact", "about", "connect", "kontakt", "station-information", "mailto:"]
#
# Define various forms embedded in blocked urls' name
#
blocklist = [
"Are you a robot",
"Cloudflare",
"Error",
"Just a moment",
"Loading",
"None",
"Not Found",
"You are being redirected"
]
#
# Set verbose and save modes to False
#
verbose = False
save = False
redo = False
#
# Declare global href and datalist to hold return values from HTML parser handler.
#
global href
datalist = []
#
# Define HTMLparser handlers
#
class MyHTMLParser(HTMLParser):
#
def handle_starttag(self, tag, attrs):
global href
if tag == "a":
for attr in attrs:
if attr[0] == "href" and attr[1] != "":
href = attr[1]
if verbose:
print ("href = ", href)
#
def handle_data(self, data):
global datalist
datalist.append(data)
#
# fetchurl(url) - Fetches the specified url, catches exceptions, and if successful checks if the content is plaintext.
# Returns success (True or False), exception (True or False), the request response, and error string.
#
# Valid success & exception states (cannot have both success = True and exception = True):
#
# success = False, exception = False - 404 error or not plaintext.
# success = True, exception = False - trust.txt file found
# success = False, exception = True - connection error occured trying to connect to site
#
def fetchurl(url):
#
if (verbose):
print ("fetchurl:url =", url)
#
# Set User Agent to "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:93.0) Gecko/20100101 Firefox/93.0" to avoid 403 errors on some websites.
#
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:93.0) Gecko/20100101 Firefox/93.0'}
#
# Try fetcing the trust.txt file, catch relevant exceptions, if there are no exceptions
# write the response text to the trust.txt file and check if the content is plaintext.
#
success = True
exception = False
error = ""
try:
r = requests.get(url, timeout=61, verify=False, headers=headers)
except requests.exceptions.TooManyRedirects as Argument:
error = "HTTP GET too many redirects exception occurred: " + str(Argument)
r = ""
success = False
exception = True
except requests.exceptions.Timeout as Argument:
error = "HTTP GET time out exception occurred: " + str(Argument)
r = ""
success = False
exception = True
except requests.exceptions.ConnectionError as Argument:
error = "HTTP GET connection error exception occurred: " + str(Argument)
r = ""
success = False
exception = True
#
if (verbose):
print ("fetcurl:success = ", success, "exception = ", exception, "error = ", error)
#
# Return results
#
return success, exception, r, error
#
# write_trust_txt (website, contact, links, vendor, copyright, cntrldby, csvfile) - Write the trust.txt file.
#
def write_trust_txt (name, website, contact, links, vendor, copyright, controls, cntrldby, members, belongtos, dta, output):
if verbose:
print ("write_trust_txt:name = ", name, "website = ", website, "contact= ", contact, "links = ", links, "vendor = ", vendor, "copyright = ", copyright, " controls = ", controls, "cntrldby = ", cntrldby, "members = ", members, "belongtos = ", belongtos)
#
# Define trust.txt file header and commment text
#
header = "# NAME trust.txt file\n#\n# For more information on trust.txt see:\n# 1. https://journallist.net - Home of the trust.txt specification\n# 2. https://datatracker.ietf.org/doc/html/rfc8615 - IETF RFC 8615 - Well-Known Uniform Resource Identifiers (URIs)\n# 3. https://www.iana.org/assignments/well-known-uris/well-known-uris.xhtml - IANA's list of registered Well-Known URIs\n#\n"
contolledby = "# NAME is controlled by the following organization\n#\n"
control = "# NAME controls the following organizations\n#\n"
belongto = "# NAME belongs to the following organizations\n#\n"
member = "# NAME has the following organizations as members\n#\n"
social = "# NAME social networks\n#\n"
vndr = "#\n# NAME vendors\n#\n"
cntct = "#\n# NAME contact info\n#\n"
datatrainingallowed = "#\n# NAME AI disclosure\n#\n"
#
# Write header
#
output.write (header.replace("NAME",name))
#
# If there is are sites that are controlled, write the "control="" entries
#
if len(controls) > 0:
output.write (control.replace("NAME",name))
for cntrl in controls:
output.write ("control=" + cntrl + "\n")
output.write("#\n")
#
# If there is a controlling site, write the "controlledby="" entry
#
if cntrldby != "" and cntrldby != "None":
output.write (contolledby.replace("NAME",name))
output.write ("controlledby=" + cntrldby + "\n#\n")
#
# If there are members, write the "member=" entries
#
if len(members) > 0:
output.write (member.replace("NAME",name))
for membr in members:
output.write ("member=" + membr + "\n")
output.write("#\n")
#
# Write "belongto="" entry
#
output.write (belongto.replace("NAME",name))
if len(belongtos) > 0:
for blongto in belongtos:
output.write ("belongto=" + blongto + "\n")
else:
output.write ("# belongto= \n")
output.write("#\n")
#
# Write "social=" entries
#
output.write (social.replace("NAME",name))
nosocial = True
for link in links:
if link != "":
output.write ("social=" + link + "\n")
nosocial = False
if nosocial:
output.write ("# social=\n")
#
# Write "vendor=" entry
#
output.write (vndr.replace("NAME",name))
if vendor != "":
output.write ("vendor=" + vendor + "\n")
else:
output.write ("# vendor=\n")
#
# Write "contact=" entry
#
output.write (cntct.replace("NAME",name))
if contact != "":
output.write ("contact=" + contact + "\n")
else:
output.write ("# contact=\n")
#
# Write "datatrainingallowed="
#
output.write (datatrainingallowed.replace("NAME",name))
if dta != "" and dta != "None" and (dta == "yes" or dta == "no"):
output.write ("datatrainingallowed=" + dta + "\n")
else:
output.write ("# datatrainingallowed=\n")
#
# Write copyright if present
#
if copyright != "":
output.write ("#\n# " + copyright + "\n")
#
# findurl (string,soup) - Find "href=" followed by a URL containing str in HTML soup, return url or "" if none found.
#
def findurl(string,soup):
global href
#
# Find all occurances of "href=" followed by a url containing string
#
tags = soup.find_all(href=re.compile(string))
#
if (verbose):
print ("findurl:string = ", string, "tags =", tags)
#
href = ""
if len(tags) > 0:
#
# Check each occurance for a valid match
#
for tag in tags:
#
# Parse HTML for this tag and get url from href
#
url = html.unescape(str(tag))
parser = MyHTMLParser()
parser.feed(url)
url = href
#
if url.startswith("/click?url="):
url = url[11:len(url)]
#
# Check for exception match or if the string is not in the found url, if so check next match
#
if string.endswith(".com"):
teststr = string[0:len(string)-4]
else:
teststr = string
#
if url in exceptions or teststr not in url:
url = ""
else:
#
# Check for embedded exceptions, if not found return url, otherwise check next match
#
found = False
for excptn in embedded:
if url.find(excptn) > 0:
found = True
if not found:
break
else:
url = ""
else:
url = ""
#
# Do final cleanup
#
if url != "":
#
# Strip after "?" or "#"
#
index = url.find("?")
if index > 0:
url = url[0:index]
index = url.find("#")
if index > 0:
url = url[0:index]
#
# Prepend "https:" to url if missing
#
if url.startswith("//"):
url = "https:" + url
#
# Don't unquote urls with "%2C" (commas), otherwise unquote them
#
if url.find("%2C") < 0:
url = unquote(url)
#
if (verbose):
print("findurl:url = ", url)
#
return (url)
#
# findcontact(soup) - Find contact URL in HTML soup, return url or "" if none found.
#
def findcontact(rurl,soup):
#
# Find contact link
#
for cntct in contactlist:
contact = findurl(cntct,soup)
if contact != "":
#
# If an absolute url prepend domain url
#
if contact.startswith("/"):
index1 = rurl.find("://") + 3
index2 = rurl[index1:len(rurl)].find("/")
baseurl = rurl[0:index1+index2]
if baseurl.endswith("/"):
contact = baseurl + contact[1:len(contact)]
else:
contact = baseurl + contact
elif contact.startswith("./"):
if url.endswith("/"):
contact = rurl + contact[2:len(contact)]
else:
contact = rurl + contact[1:len(contact)]
elif contact.startswith("#") or contact.startswith("a") or contact.startswith("c"):
if url.endswith("/"):
contact = rurl + contact
else:
contact = rurl + "/" + contact
break
return(contact)
#
# findtel (text) - Find telephone number in HTML text, return tel:<phone number>
#
def findtel(text):
#
# Find all occurances of xxx-xxx-xxxx or (xxx) xxx-xxxx
#
list = re.findall("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]",text)
if len(list) !=0:
phone = "tel:" + list[0].strip()
else:
list = re.findall("\\([0-9][0-9][0-9]\\) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]",text)
if len(list) !=0:
phone = "tel:" + list[0].strip()
else:
phone = ""
#
if (verbose):
print("findtel:phone = ", phone)
#
return(phone)
#
# findcopyright (text) - Find copyright text in HTML text, return copyright string
#
# Obsserved Copyright forms:
# 1. "copyright [0-9]{4}"
# 2. "copyright © [0-9]{4}"
# 3. "copyright ©[0-9]{4}"
# 4. "copyright ©"
# 4. "copyright (c) [0-9]{4}"
# 5. "© [0-9]{4}"
# 6. "©[0-9]{4}"
# 7. "© copyright"
# 8. "©"
#
def findcopyright(text):
#
# Define various forms of "copyright"
#
copyrightlist = ["copyright [0-9]{4}", "copyright © [0-9]{4}", "copyright ©[0-9]{4}", "copyright ©", "copyright (c) [0-9]{4}", "© [0-9]{4}", "©[0-9]{4}", "© copyright", "©"]
#
# Initialize variables
#
copyright = ""
#
# Remove newlines, some unnecessary characters (¬ †), comments, scripts, and embedded links
#
text = re.sub(re.compile("[¬|†|\n|\r|]")," ",text)
text = re.sub(re.compile("<!--[^-]*-->"),"",text)
text = re.sub(re.compile("/\\* [^\\*]*\\*/"),"",text)
text = re.sub(re.compile("<script>[^>]*</script>"),"",text)
text = re.sub(re.compile("<a [^>]*>"),"",text)
#
# Step through copyright list to check its various forms
#
for string in copyrightlist:
#
if (verbose):
print ("findcopyright:string = ", string)
#
list = re.findall(re.compile(">[^>]*" + string + "[^<]*<",re.IGNORECASE),text)
#
if (verbose):
print ("findcopyright:list = ", list)
#
for copyright in list:
#
# If match has an "http" link or "-copyright" or "SiteCatalyst", check next match
#
if copyright.find("http") < 0 and copyright.find("-copyright") < 0 and copyright.find("SiteCatalyst") < 0:
#
# Check for "<meta name=\"copyright\" content=" and remove it
#
if copyright.find("<meta name=\"copyright\" content=") >= 0:
copyright = copyright.replace("<meta name=\"copyright\" content=","")
copyright = copyright.replace("/>","")
copyright = copyright.replace("\"","")
#
# Check for "<meta name=\"rights\" content=" and remove it
#
if copyright.find("<meta name=\"rights\" content=") >= 0:
copyright = copyright.replace("<meta name=\"rights\" content=","")
copyright = copyright.replace("/>","")
copyright = copyright.replace("\"","")
#
# Remove leading ">" and trailing "<", strip extraneous spaces
#
copyright = copyright[1:len(copyright)-1]
copyright = copyright.strip()
copyright = re.sub("\\s+"," ",copyright)
#
break
else:
copyright = ""
if copyright != "":
break
#
if (verbose):
print ("findcopyright:copyright =", copyright)
#
return(copyright)
#
# trustfilename(url) - generate a trust.txt filename from url
#
def trustfilename(url,dirname):
#
# Create output trust.txt filename from url "www.basedomain-trust.txt", e.g., "www.journallist.net-trust.txt"
#
o = urlparse(url)
if o.scheme == "":
s = o.path.split("/",1)
domain = s[0]
else:
domain = o.netloc
if domain.startswith("www."):
filename = dirname + "/" + domain + "-trust.txt"
else:
filename = dirname + "/www." + domain + "-trust.txt"
return (filename)
#
# htmlfilenam(url) - generate an filename from url
#
def htmlfilename(url,dirname):
#
# Create output HTML filename from url
#
o = urlparse(url)
if o.scheme == "":
s = o.path.split("/",1)
domain = s[0]
else:
domain = o.netloc
if domain.startswith("www."):
filename = dirname + "/" + domain + ".html"
else:
filename = dirname + "/www." + domain + ".html"
return (filename)
#
# readurl(url) - Reads the content of the specified url
#
# Returns success (True or False), exception (True or False), the request response, and error string.
#
# Valid success & exception states (cannot have both success = True and exception = True):
#
# success = True, exception = False - trust.txt file found
# success = False, exception = True - connection error occured trying to connect to site
#
def readurl(url,dirname):
#
if (verbose):
print ("readurl:url =", url, "dirname = ", dirname)
#
# Get HTML filename
#
filename = htmlfilename(url,dirname)
#
if os.path.isfile(filename):
success = True
error = ""
#
# Open HTML file and read contents
#
file = open(filename,"r")
text = file.read()
file.close()
else:
success = False
error = "file: ", filename, "not found"
text = ""
#
# Return results
#
return success, text, error
#
# process(url) - Process the given url to find all the social, contact, and vendor links
#
def process (url,dirname):
#
if (verbose):
print ("process:url = ", url)
#
rurl = url
text = ""
name = ""
contact = ""
links = []
vendor = ""
copyright = ""
cntrl = ""
cntrldby = ""
#
# If redo, read contents of HTML file previously saved, Fetch home page
#
if redo:
success, text, error = readurl(url,dirname)
exception = False
else:
success, exception, r, error = fetchurl(url)
if success:
rurl = r.url
text = r.text
#
# If successful, find links
#
if success:
#
skip = False
#
# Remove text after "?" or "#" or ":443" from returned url
#
index = rurl.find("?")
if index > 0:
rurl = rurl[0:index-1]
index = rurl.find("#")
if index > 0:
rurl = rurl[0:index-1]
index = rurl.find(":443")
if index > 0:
rurl = rurl[0:index]
#
# Save file if -s option used
#
if save:
#
# If save HTML, create output filename from url, prepend dirname, and write response
#
filename = htmlfilename(rurl,dirname)
file = open(filename,"w")
file.write(r.text)
file.close()
#
# Check for errors
#
for error in errors:
if (text.find(error) >= 0):
skip = True
print ("Error for ", url, ":", error)
#
# Check for domain registrar redirects
#
for registrar in registrars:
if (rurl.find(registrar) >= 0):
skip = True
print ("Redirect ", url, " to domain registrar: ", registrar)
break
#
if not skip:
#
# Unescape HTML escaped characters
#
untext = html.unescape(text)
soup = BeautifulSoup(untext)
#
# Get title, strip "<title>" and "</title>" to get name
#
name = html.unescape(str(soup.title))
#
name = re.sub("<title[^>]*>","",name,1)
name = name.replace("</title>","")
name = name.replace("\n","")
name = name.replace("\r","")
name = name.replace(","," ")
#
# Remove home page designation from name
#
for home in homepage:
name = re.sub(re.compile(home,re.IGNORECASE),"",name)
#
# Strip leading and trailing spaces
#
name = name.strip()
#
# Check if name indicates site was blocked
#
blocked = False
for block in blocklist:
if name.find(block) >=0:
blocked = True
break
if blocked:
name = "Site Blocked"
print ("Site Blocked: ", url)
#
if verbose:
print ("name = ", name)
#
# Find contact link
#
contact = findcontact(rurl,soup)
#
# If not found, look for a telephone number
#
if contact == "":
contact = findtel(untext)
#
if verbose:
print ("contact = ", contact)
#
# Find social network links
#
links = []
for social in socials:
socialurl = findurl(social,soup)
#
# If not found try removing ".com" and prepending "/"
#
if socialurl == "":
social = "/" + social[0:len(social)-4]
socialurl = findurl(social,soup)
#
# If found starting with "/" prepend baseurl
#
if socialurl.startswith("/"):
index1 = rurl.find("://") + 3
index2 = rurl[index1:len(rurl)].find("/")
baseurl = rurl[0:index1+index2]
if baseurl.endswith("/"):
socialurl = baseurl + socialurl[1:len(socialurl)]
else:
socialurl = baseurl + socialurl
links.append(socialurl)
#
if verbose:
print ("links = ", links)
#
# Find if there is a vendor link
#
vendor = ""
for link in vendors:
if (untext.find(link) >= 0):
vendor = "https://www." + link + "/"
break
#
if verbose:
print ("vendor = ", vendor)
#
# Find Copyright
#
copyright = findcopyright(untext).replace(","," ")
#
if verbose:
print ("vendor = ", vendor)
#
# Check if copyright contains a chain
#
cntrldby = ""
for chain in chains.keys():
if (copyright.find(chain) >= 0):
cntrldby = chains[chain]
#
if verbose:
print ("cntrldby = ", cntrldby)
else:
skip = True
rurl = url
name = ""
contact = ""
links = []
vendor = ""
copyright = ""
cntrl = ""
cntrldby = ""
if exception:
copyright = error.replace(","," ")
#
if (verbose):
print ("process:rurl = ", rurl, "name = ", name, "contact= ", contact, "links = ", links, "vendor = ", vendor, "copyright = ", copyright, "cntrl = ", cntrl, "cntrldby = ", cntrldby, "skip = ", skip)
#
return rurl, name, contact, links, vendor, copyright, cntrl, cntrldby, skip
#
# chkecosys (url, ecosys) - Check for url in ecosystem, if present return attributes discovered
#
def chkecosys (url, ecosys):
#
# Initialize variables
#
contact = ""
links = []
vendor = ""
controls = []
controlledby = ""
members = []
belongtos = []
o = urlparse(url)
if o.scheme == "":
s = o.path.split("/",1)
domain = s[0]
else:
domain = o.netloc
found = False
#
if verbose:
print ("chkecosys:domain = ", domain)
#
for entry in ecosys:
#
# Split entry into srcurl, attr, refurl
#
entry = entry.strip("\n")
temp = entry.split(",",2)
#
srcurl = temp[0]
attr = temp[1]
refurl = temp[2]
#
# Check if domain is in the srcurl
#
if srcurl.find(domain) > 0:
#
# If this is a srcurl, then capture attributes of existing trust.txt file
#
found = True
if attr == "belongto" and refurl not in belongtos:
belongtos.append(refurl)
elif attr == "member" and refurl not in members:
members.append(refurl)
elif attr == "social" and refurl not in links:
links.append(refurl)
elif attr == "contact":
contact = refurl
elif attr == "control" and refurl not in controls:
controls.append(refurl)
elif attr == "controlledby":
controlledby = refurl
elif attr == "vendor":
vendor = refurl
#
# Check if url is the refurl in a member entry in the ecosystem, if so append the srcurl to the belongtos list if not already present
#
if refurl.find(domain) > 0 and attr == "member" and srcurl not in belongtos:
found = True
belongtos.append(srcurl)
#
if verbose:
print ("contact = ", contact, "links = ", links, "vendor", vendor, "control = ", controls, "controlledby = ", controlledby, "members = ", members, "belongtos = ", belongtos)
#
if found:
print ("Found: ", url, "in ecosystem")
#
return found, contact, links, vendor, controls, controlledby, members, belongtos
#
# Main program
#
# To limit the number of columns in the output.csv file, set the maximum number of "control", "belongto", and "member" columns to match the number of "social" columns
#
maxsocial = len (socials)
maxcontrol = maxsocial
maxbelongto = maxsocial
maxmember = maxsocial
#
# Ignore warnings
#
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
#
# Create argument parser
#
parser = argparse.ArgumentParser(description="Scrapes websites to discover: 'name', 'contact', 'social', and 'copyright' and writes trust.txt file. Optionally, checks webcrawler ouptut for additional 'belongto' entries.")
parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
parser.add_argument("-s", "--save", help="save HTML from the website", action="store_true")
parser.add_argument("-r", "--redo", help="redo generation of trust.txt files from HTML previously saved with -s option", action="store_true")
parser.add_argument("-j", "--forcejl", help="force belongto=https://www.journallist.net/", action="store_true")
parser.add_argument("-a", "--ai", help="datatrainingallowed attribute, AI = [\"yes\"|\"no\"]", type=str, action="store")
parser.add_argument("-c", "--curl", help="force controlledby=CURL", type=str, action="store")
parser.add_argument("-b", "--burl", help="force belongto=BURL", type=str, action="store")
parser.add_argument("-d", "--dirname", help="name of directory to write output, defualt to current directory", type=str, action="store")
parser.add_argument("-w", "--webcrawl", help="name of webcrawler output directory to check for belongto entries", type=str, action="store")
parser.add_argument("url_or_filename", help="url to scrape or name of a .csv file containing a list of urls to scape", type=str, action="store")
#
# Parse arguments
#
args = parser.parse_args()
#
verbose = args.verbose
redo = args.redo
if redo:
save = False