-
Notifications
You must be signed in to change notification settings - Fork 0
/
PACER-selenium.py
702 lines (579 loc) · 23.9 KB
/
PACER-selenium.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
from selenium import webdriver
import random
import time
from bs4 import BeautifulSoup
import os
import csv
import datetime
from send_email import send_email
import glob
import subprocess
import re
from pyvirtualdisplay import Display
import sys
def sift_chars(fname_str):
'''
ensures filename is legal, replaces all with hyphens
'''
illegal_chars = "%><!`&*‘|{}?“=\/:@'" + '"'
for c in illegal_chars:
fname_str = fname_str.replace(c, "-")
return fname_str
def login_to_pacer(login_user, login_password, dl_directory):
'''
simply logs into the pacer system for any court
'''
display = Display(visible=0, size=(800, 600))
display.start()
# CHROME setup driver
chrome_profile = webdriver.ChromeOptions()
profile = {
"download.default_directory": dl_directory,
"download.prompt_for_download": False,
"directory_upgrade": True,
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True}
chrome_profile.add_experimental_option("prefs", profile)
driver = webdriver.Chrome(
chrome_options=chrome_profile,
executable_path="./chromedriver")
# FIREFOX
# profile = webdriver.FirefoxProfile()
# profile.set_preference('browser.download.folderList', 2)
# profile.set_preference('browser.download.manager.showWhenStarting', False)
# profile.set_preference("browser.download.dir", dl_directory)
# profile.set_preference(
# "browser.helperApps.neverAsk.saveToDisk",
# "application/pdf")
# profile.set_preference("pdfjs.disabled", True)
# profile.set_preference("plugin.scan.plid.all", False)
# profile.set_preference("plugin.scan.Acrobat", "99")
# driver = webdriver.Firefox(firefox_profile=profile,
# firefox_binary='./firefox/firefox',
# executable_path="./geckodriver")
# login to pacer website
login_url = "https://pacer.login.uscourts.gov/csologin/login.jsf"
driver.get(login_url)
driver.find_element_by_name("login:loginName").send_keys(login_user)
driver.find_element_by_name("login:password").send_keys(login_password)
driver.find_element_by_name('login:fbtnLogin').click()
time.sleep(1)
return driver
def get_docket_rows(driver, case_num, year, court_perl):
'''
goes to specific court perl script and extracts docket rows for specific case.
can be used for main case and associated cases
'''
# execute if not getting rows for associated cases
if case_num:
# Western District Texas Court, start loop for cases here
driver.get(court_perl)
driver.find_element_by_name("case_num").clear()
driver.find_element_by_name("case_num").send_keys(case_num)
driver.find_element_by_id('case_number_find_button_0').click()
# wait until case is found and number is changed
count = 0
while driver.find_element_by_name(
"case_num").get_attribute('value') == case_num:
time.sleep(1)
count += 1
if count > 30:
break
time.sleep(1) # case has been found, proceed
driver.find_element_by_name("date_from").clear()
driver.find_element_by_name("date_from").send_keys("01/01/1990")
driver.find_element_by_name("date_to").clear()
driver.find_element_by_name("date_to").send_keys(
datetime.date.today().strftime("%m/%d/%Y"))
time.sleep(1)
driver.find_element_by_name('button1').click()
# get source to get docket info
docket_source = str(driver.page_source)
soup = BeautifulSoup(docket_source, 'html5lib')
# set start for row, will change if scrape was interrupted
row_start = 0
# get associated cases if main case
if case_num:
with open(district + "/" + je_id + "/" + je_id + "_data.csv", 'r', encoding="utf-8") as f:
reader = csv.reader(f)
data = list(reader)
if len(data) == 1:
get_associated_cases(soup)
# save docket source if main case
with open(district + "/" + je_id + "/" + str(je_id) + ".html", "w", encoding="utf-8") as f:
f.write(docket_source)
else:
row_start = len(data) - 1
else:
if os.path.exists(
district +
"/" +
je_id +
"/associated/" +
str(case_num) +
"/" +
'assoc_data.csv'):
with open(district + "/" + je_id + "/associated/" + str(case_num) + "/" + 'assoc_data.csv', 'r', encoding="utf-8") as f:
reader = csv.reader(f)
data = list(reader)
row_start = len(data) - 1
docket_rows = []
for i in range(len(soup.findAll("table")) - 5):
# table is broken up to sets of 100 rows, don't want first 4 or last
ind = i + 4
docket_table = soup.findAll("table")[ind]
docket_headers = ("Filing Date", "#", "Docket Text")
# get table info in dict
for row in docket_table.findAll("tr"):
row_data = []
for i, column in enumerate(row.findAll("td")):
if i == 0:
row_data.append(column.text)
elif i == 2:
cell_urls = {}
urls = column.findAll("a")
for u in urls:
cell_urls[u.text.strip()] = u.get("href")
row_data.append((column.text.strip(), cell_urls))
elif i > 2:
row_data.append(column.text.strip())
if len(row_data) > 0:
docket_rows.append(tuple(row_data))
return docket_rows[row_start:]
def process_link(
link_str,
base_url,
district,
already_scraped,
adversary=False,
dock_num=False):
'''
takes any links to documents, and downloads them into file structure
'''
if link_str.startswith("https://"):
pass
else:
link_str = base_url + link_str
driver.get(link_str)
f_paths = []
if "Multiple Documents" in str(driver.page_source):
soup = BeautifulSoup(str(driver.page_source), 'html5lib')
doc_table = soup.findAll("tr")
for r in doc_table:
if "href" in str(r):
tds = r.findAll("td")
doc_url = tds[0].a["href"]
dl_id = doc_url.split("/")[-1]
if dl_id not in already_scraped:
os.system('rm *.pdf')
if doc_url.startswith("https://"):
driver.get(doc_url)
driver.find_element_by_xpath(
'//*[@id="cmecfMainContent"]/form/input').click()
else:
doc_url = base_url + doc_url
driver.get(doc_url)
driver.find_element_by_xpath(
'//*[@id="cmecfMainContent"]/form/input').click()
file_name = tds[2].text
new_name = sift_chars(file_name.strip()) + ".pdf"
# if not associated case
# create file structure
if not adversary:
if not os.path.exists(
district + "/" + je_id + "/" + docket_number):
os.makedirs(
district + "/" + je_id + "/" + docket_number)
new_path = district + "/" + je_id + "/" + docket_number + "/" + new_name
else:
if not os.path.exists(
district +
"/" +
je_id +
"/associated/" +
adversary +
"/" +
dock_num):
os.makedirs(
district +
"/" +
je_id +
"/associated/" +
adversary +
"/" +
dock_num)
new_path = district + "/" + je_id + "/associated/" + \
adversary + "/" + dock_num + "/" + new_name
# wait for file to download
counter = 0
while len(glob.glob("*.pdf")) == 0:
time.sleep(1)
counter += 1
if counter > 500:
break
time.sleep(4)
download_name = glob.glob("*.pdf")[0]
os.rename(
download_name, re.sub(
r'[^\x00-\x7f]', '-', new_path))
already_scraped.append(dl_id)
f_paths.append(new_path)
time.sleep(1)
os.system('rm *.pdf')
time.sleep(1)
else:
soup = BeautifulSoup(str(driver.page_source), 'html5lib')
restricted = False
try:
dl_id = soup.find("form")["action"].split("/")[-1]
except:
if "The document is restricted" in driver.page_source:
restricted = True
elif "document is not available" in driver.page_source:
restricted = True
if not restricted:
os.system('rm *.pdf')
driver.find_element_by_xpath(
'//*[@id="cmecfMainContent"]/form/input').click()
if dl_id not in already_scraped:
# create file structure
if not adversary:
if not os.path.exists(
district + "/" + je_id + "/" + docket_number):
os.makedirs(
district + "/" + je_id + "/" + docket_number)
new_path = district + "/" + je_id + "/" + docket_number + "/Main Document.pdf"
else:
if not os.path.exists(
district +
"/" +
je_id +
"/associated/" +
adversary +
"/" +
dock_num):
os.makedirs(
district +
"/" +
je_id +
"/associated/" +
adversary +
"/" +
dock_num)
new_path = district + "/" + je_id + "/associated/" + \
adversary + "/" + dock_num + "/Main Document.pdf"
# wait for file to download
counter = 0
while len(glob.glob("*.pdf")) == 0:
time.sleep(1)
counter += 1
if counter > 500:
break
time.sleep(4)
download_name = glob.glob("*.pdf")[0]
os.rename(
download_name, re.sub(
r'[^\x00-\x7f]', '-', new_path))
already_scraped.append(dl_id)
f_paths.append(new_path)
time.sleep(1)
os.system('rm *.pdf')
time.sleep(1)
else:
f_paths.append("RESTRICTED")
time.sleep(5)
return (f_paths, already_scraped)
def get_associated_cases(soup):
ass_exist = True
try:
ass_cases_ext = soup.findAll("div", {"class": "noprint"})[
1].find("a")["href"]
except:
ass_exist = False
if ass_exist:
driver.get(base_url + ass_cases_ext)
driver.find_element_by_xpath('//*[@id="referrer_form"]/p/a').click()
soup = BeautifulSoup(str(driver.page_source), "html5lib")
assoc_rows = soup.find("table").findAll("tr")
if not os.path.exists(district + "/" + je_id + "/" + "associated"):
os.makedirs(district + "/" + je_id + "/" + "associated")
with open(district + "/" + je_id + "/" + str(je_id) + "_associated_cases.html", "w", encoding="utf-8") as f:
f.write(str(driver.page_source))
# if interrupted start from where last row
if os.path.exists(
str(district) +
"/" +
str(je_id) +
"/" +
str(je_id) +
'_associated_cases.csv'):
with open(str(district) + "/" + str(je_id) + "/" + str(je_id) + '_associated_cases.csv', 'r', encoding="utf-8") as f:
reader = csv.reader(f)
data = list(reader)
if len(data) - 1 == len(assoc_rows):
assoc_rows = [assoc_rows[-1]]
else:
assoc_rows = assoc_rows[len(data) - 2:]
else:
with open(str(district) + "/" + str(je_id) + "/" + str(je_id) + '_associated_cases.csv', 'a', encoding="utf-8") as f:
w = csv.writer(f, delimiter=',')
header = (
"je_id",
"Related Case No",
"Caption",
"Type",
"Judge",
"Plaintiff",
"Defendant",
"Plaintiff Lawyer",
"Defendant Lawyer",
"Date Filed",
"Date Terminated",
"Nature of Suit")
w.writerow(header)
for row in assoc_rows: # CHANGE FOR FULL
columns = row.findAll("td")
if len(columns) > 0:
case_ext = columns[1].find("a")["href"]
case_num = columns[1].find("a").text
caption = ' '.join(columns[1].text.split()[1:])
case_type = columns[2].text
row_to_write = (je_id, case_num, caption, case_type)
with open(str(district) + "/" + str(je_id) + "/" + str(je_id) + '_associated_cases.csv', 'a', encoding="utf-8") as f:
w = csv.writer(f, delimiter=',')
w.writerow(row_to_write)
driver.get(base_url + case_ext)
docket_rows = get_docket_rows(
driver=driver,
case_num=False,
year=False,
court_perl=False)
if not os.path.exists(
district + "/" + je_id + "/associated/" + case_num):
os.makedirs(
district + "/" + je_id + "/associated/" + case_num)
with open(district + "/" + je_id + "/associated/" + case_num + "/" + str(case_num) + ".html", "w", encoding="utf-8") as f:
f.write(str(driver.page_source))
if os.path.exists(
district +
"/" +
je_id +
"/associated/" +
str(case_num) +
"/" +
'assoc_data.csv'):
with open(district + "/" + je_id + "/associated/" + str(case_num) + "/" + 'assoc_data.csv', 'r', encoding="utf-8") as f:
reader = csv.reader(f)
data = list(reader)
docket_rows = docket_rows[len(data) - 1:]
else:
with open(district + "/" + je_id + "/associated/" + str(case_num) + "/" + 'assoc_data.csv', 'a', encoding="utf-8") as f:
w = csv.writer(f, delimiter=',')
header = (
"je_id",
"case_num",
"docket_text",
"docket_number",
"docket_date",
"file_link",
"[lawfirm1]",
"[lawyers1]",
"[lawfirm2]",
"[lawyers2]",
"[lawfirm3]",
"[lawyers3]",
"[moving party]",
"[motion caption]")
w.writerow(header)
for row in docket_rows: # just 20 rows CHANGE FOR FULL
docket_date = row[0]
docket_text = row[2].strip()
if len(
row[1]) > 1 and len(
row[1][0]) > 0 and row[1][0][0].isdigit():
docket_number = row[1][0].split()[0]
else:
with open(district + "/" + je_id + "/associated/" + str(case_num) + "/" + 'assoc_data.csv', 'r', encoding="utf-8") as f:
reader = csv.reader(f)
temp_data = list(reader)
docket_number = temp_data[-1][-3]
already_scraped = []
paths = []
for c in row:
if len(c) > 1 and isinstance(
c[1], dict) and len(
c[1]) > 0:
for k in c[1].keys():
url = c[1][k]
res = process_link(
link_str=url,
base_url=base_url,
district=district,
already_scraped=already_scraped,
dock_num=docket_number,
adversary=case_num)
file_paths = res[0]
if len(file_paths) > 0:
already_scraped = res[1]
paths.extend(file_paths)
# wait after each link call
time.sleep(random.randint(1, 3))
csv_row = [
je_id,
case_num,
docket_text,
docket_number,
docket_date,
"; ".join(paths)]
scraped_data[district].append(csv_row)
with open(district + "/" + je_id + "/associated/" + str(case_num) + "/" + 'assoc_data.csv', 'a', encoding="utf-8") as f:
w = csv.writer(f, delimiter=',')
w.writerow(csv_row)
time.sleep(random.randint(1, 3))
# In[ ]:
# main program
# for case num info
with open('dataset.csv', 'r', encoding="utf-8") as f:
reader = csv.reader(f)
data = list(reader)
with open('distlogin.csv', 'r', encoding="utf-8") as f:
reader = csv.reader(f)
distlogin_csv = list(reader)
with open('completed', 'r') as f:
completed_cases = f.read().split('\n')
email_address = distlogin_csv[0][0]
email_password = distlogin_csv[0][1]
dl_directory = distlogin_csv[0][2]
district = distlogin_csv[1][0]
# change for each district
dist_data = [x for x in data if x[-2] == district]
district = ''.join(district.split())
distlogin = {}
for r in distlogin_csv[1:]:
distlogin[district] = {"login": r[1],
"pw": r[2],
"base_url": r[3]}
# prepare and loop
scraped_data = {}
scraped_data[district] = []
if not os.path.exists(district):
os.makedirs(district)
driver = login_to_pacer(
login_user=distlogin[district]["login"],
login_password=distlogin[district]["pw"],
dl_directory=dl_directory)
for case in dist_data: # just two cases CHANGE FOR FULL
print(datetime.datetime.time(datetime.datetime.now()))
company = case[0]
je_id = case[1]
case_num = case[2]
petition_date = case[3]
year = case[6]
if je_id not in completed_cases:
send_email(
email_address,
email_password,
email_address,
"New Case",
"JEID" +
str(je_id))
if not os.path.exists(district + "/" + je_id):
os.makedirs(district + "/" + je_id)
if not os.path.exists(
district +
"/" +
je_id +
"/" +
je_id +
"_data.csv"):
# for output data
with open(district + "/" + je_id + "/" + je_id + "_data.csv", 'w', encoding="utf-8") as f:
w = csv.writer(f, delimiter=',')
header = (
"Company",
"je_id",
"petition_date",
"casenum",
"xdistfiled",
"docket_text",
"docket_number",
"docket_date",
"file_link",
"[lawfirm1]",
"[lawyers1]",
"[lawfirm2]",
"[lawyers2]",
"[lawfirm3]",
"[lawyers3]",
"[moving party]",
"[motion caption]")
w.writerow(header)
# change for each district
base_url = distlogin[district]["base_url"]
court_perl = base_url + "/cgi-bin/DktRpt.pl"
docket_rows = get_docket_rows(
driver=driver,
case_num=case_num,
year=year,
court_perl=court_perl)
for row in docket_rows: # just 20 rows CHANGE FOR FULL
docket_date = row[0]
docket_text = row[2].strip()
if len(
row[1]) > 1 and len(
row[1][0]) > 0 and row[1][0][0].isdigit():
docket_number = row[1][0].split()[0]
else:
with open(district + "/" + je_id + "/" + je_id + "_data.csv", 'r', encoding="utf-8") as f:
reader = csv.reader(f)
temp_data = list(reader)
docket_number = temp_data[-1][-3]
already_scraped = []
paths = []
for c in row:
if len(c) > 1 and isinstance(c[1], dict) and len(c[1]) > 0:
for k in c[1].keys():
url = c[1][k]
res = process_link(
link_str=url,
base_url=base_url,
district=district,
already_scraped=already_scraped)
file_paths = res[0]
if len(file_paths) > 0:
already_scraped = res[1]
paths.extend(file_paths)
# wait after each link call
time.sleep(random.randint(1, 3))
csv_row = [
company,
je_id,
petition_date,
case_num,
district,
docket_text,
docket_number,
docket_date,
"; ".join(paths)]
scraped_data[district].append(csv_row)
with open(district + "/" + je_id + "/" + je_id + "_data.csv", 'a', encoding="utf-8") as f:
w = csv.writer(f, delimiter=',')
w.writerow(csv_row)
with open('completed', 'a') as f:
f.write('\n' + je_id)
# zip and push to box
p = subprocess.Popen(['bash',
'zip-push.sh',
je_id],
stdin=None,
stdout=None,
stderr=None,
close_fds=True)
send_email(
email_address,
email_password,
email_address,
"Finished",
"Done scraping." +
str(je_id))
print(datetime.datetime.time(datetime.datetime.now()))