-
Notifications
You must be signed in to change notification settings - Fork 2
/
pylitreview.py
817 lines (673 loc) · 26.9 KB
/
pylitreview.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
import time
import tqdm
import math
import random
import glob
import os
import numpy as np
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from enum import Enum
class SearchWhere(Enum):
Title = 1
Abstract = 2
TitleAbstract = 3 #Keywords have to be in Title OR Abstract
Text = 4
class Library(Enum):
IEEE = 1
ACM = 2
ScienceDirect = 3
globalLastLibrary = None
driver = None
DEBUG = 0
def getElement(driver, by, value, number=None, timeOut=3, maxTry=5):
"""
Get the element from the driver in a safe way by waiting for the element to appear
Attributes
----------
driver : selenium.webdriver
The selenium driver
by : selenium.webdriver.common.by
The search method
value : str
The search value
number : int, optional
The number of the element to return (default is None)
If None all elements are returned as a list
timeOut : int, optional
The time to wait for the element to appear (default is 3)
maxTry : int, optional
The maximum number of tries to find the element (default is 5)
Returns
-------
bool
True if the element was found
selenium.webdriver.element
The element if found
None if no element was found
"""
i = 0
while True:
if (number != None):
if len(driver.find_elements(by=by, value=value)) > number:
try:
element = driver.find_elements(by=by, value=value)[number]
return True, element
except:
if i >= maxTry:
print_debug(f'Error: Failed to find {value} by {by}', 0)
return False, None
else:
print_debug(f'Retrying to find to find {value} by {by}', 2)
i +=1
else:
try:
driver.find_element(by=by, value=value)
elements = driver.find_elements(by=by, value=value)
return True, elements
except NoSuchElementException:
if i >= maxTry:
print_debug(f'Warning: Failed to find {value} by {by}', 0)
return False, None
else:
print_debug(f'Retrying to find to find {value} by {by}', 2)
i +=1
time.sleep(timeOut)
return False, None
def getFileNameOutput(infos, outputFolderBib, pagenr):
"""
Get the output file name for the bib file
Attributes
----------
infos : dict
The information about the search
outputFolderBib : str
The output folder for the bib file
pagenr : int
The page number
"""
library = str(infos["Library"]).split(".")[-1].lower()
name = ("--".join(infos["Keyword"])).replace(" ","-")
searchWhere = str(infos["SearchWhere"]).split(".")[-1]
return f'{outputFolderBib}{library}_{name}_{searchWhere}_page{pagenr}_{infos["YearStart"]}-{infos["YearEnd"]}.bib'
def save_screenshot(driver, infos, path = "./screenshots/"):
"""
Save a screenshot of the current page
Attributes
----------
driver : selenium.webdriver
The selenium driver
infos : dict
The information about the search
path : str, optional
The path to save the screenshot (default is "./screenshots/")
"""
library = str(infos["Library"]).split(".")[-1]
name = "".join(infos["Keyword"])
searchWhere = str(infos["SearchWhere"]).split(".")[-1]
os.makedirs(path, exist_ok=True)
driver.save_screenshot(f"{path}{library}_{name}_{searchWhere}_{int(time.time())}.png")
def print_debug (text, level=1):
if DEBUG >= level:
print(text)
def getURLACM(infos):
"""
Get the URL for the ACM search
Attributes
----------
infos : dict
The information about the search
Returns
-------
str
The URL for the search
"""
keywords = infos["Keyword"]
concatentation="AND"
search = ""
titleSearch = "doSearch?AllField="
for i, keyword in enumerate(keywords):
search += f"%22{keyword}%22"
if (i < len(keywords)-1):
search += f"+{concatentation}+"
if infos["SearchWhere"] == SearchWhere.Title:
print_debug("Searching ACM for title only", 0)
titleSearch = f"doSearch?fillQuickSearch=false&expand=dl&field1=Title&text1={search}"
elif infos["SearchWhere"] == SearchWhere.Abstract:
print_debug("Searching ACM for abstract only", 0)
titleSearch = f"doSearch?fillQuickSearch=false&expand=dl&field1=Abstract&text1={search}"
elif infos["SearchWhere"] == SearchWhere.TitleAbstract:
titAbsDict = {SearchWhere.Title: "Title", SearchWhere.Abstract: "Abstract"}
if (infos["SearchWhere"] == SearchWhere.TitleAbstract):
lstWhere = [SearchWhere.Title, SearchWhere.Abstract]
key = ''
for i, keyword in enumerate(infos["Keyword"]):
key = key + '['
for j, w in enumerate(lstWhere):
key = f'{key}{titAbsDict[w]}:"{keyword.replace(" ", "+")}"'
if (len(lstWhere) - j > 1):
key = key + '+OR+'
key = key + ']'
if (len(infos["Keyword"]) - i > 1):
key = key + '+AND+'
key = key + ''
titleSearch = key.replace(":","%3A").replace("[","%28").replace("]","%29")
url = f'https://dl.acm.org/action/doSearch?fillQuickSearch=false&target=advanced&expand=dl&pageSize=50'
url += f'&AfterYear={infos["YearStart"]}&BeforeYear={infos["YearEnd"]}'
url += f'&AllField={titleSearch}&startPage='
return url
elif infos["SearchWhere"] == SearchWhere.Text:
print_debug("Quicksearching ACM")
raise NotImplementedError("Can't use 'set' on an ADC!")
else:
print_debug("Error: Not a supproted search type", 0)
# The url must end with the page number so we can attach the page number later
url = f'https://dl.acm.org/action/{titleSearch}&pageSize=50'
url = url + f'&AfterYear={infos["YearStart"]}&BeforeYear={infos["YearEnd"]}&startPage='
return
def loadACMBib (toOpen, driver):
"""
Load the ACM bib file
Attributes
----------
toOpen : str
The URL to open
driver : selenium.webdriver
The selenium driver
Returns
-------
bool
True if the bib file was loaded
int
0 if no results were found, 1 if results were found, -1 if an error occured
"""
try:
driver.get(toOpen)
except:
print_debug(f'Error: Failed to open {toOpen}', 0)
return False, -1
#iterate over middle navbar to see if query found paper results or only people
successElement, navMiddle = getElement(driver, by=By.CLASS_NAME, value="search-result__nav", number=0, maxTry=2)
found = False
for a in navMiddle.find_elements(by=By.TAG_NAME, value="a"):
if(a.text =="RESULTS"):
if "active" not in a.get_attribute("class"):
a.click()
found = True
break
if found == False:
return True, 0
# Select "Select All" to download all entries
successElement, element = getElement(driver, by=By.CLASS_NAME, value="item-results__checkbox", number=0)
if (successElement):
element.click()
else:
return False, -1
# Seach and click the "Export Citations" button
successElement, element = getElement(driver, by=By.CLASS_NAME, value="export-citation", number=0)
if (successElement):
element.click()
else:
return False, -1
time.sleep(5)
# Get the Download button from the overlay and Dowload the bib file
successElement, elementOverlayExport = getElement(driver, by=By.CLASS_NAME, value="exportCitation__tabs", number=0)
if (successElement):
successElement, elementButtonDownload = getElement(elementOverlayExport, by=By.CLASS_NAME, value="download__btn", number=0)
if (successElement):
elementButtonDownload.click()
else:
False, -1
else:
False, -1
return True, 1
def saveACMBib(driver, infos, outputFolderBib):
acm_maxpage = 39
keyword = [item.replace(" ", "+") for item in infos["Keyword"]]
print_debug(f"Search for: {keyword}", 1)
url = getURLACM(infos)
print_debug(url, 1)
driver.get(url)
time.sleep(7)
successElement, navbar = getElement(driver, by=By.CLASS_NAME, value="search-result__nav-container", number=0)
if not successElement:
return False, url, -1
successElement, navelements = getElement(navbar, by=By.XPATH, value=".//*", number=None)
if not successElement:
return False, url, -1
foundResults = False
for nav_element in navelements:
if "RESULTS" in nav_element.text:
foundResults = True
if foundResults == False:
print_debug("Only people in results - next keyword", 2)
return False, url, -1
save_screenshot(driver, infos)
successElement, searchResultCount = getElement(driver, by=By.CLASS_NAME, value="result__count", number=0)
if not successElement:
return False, url, -1
searchResultCount = searchResultCount.text.split(" ")[0]
if "," in searchResultCount:
searchResultCount = searchResultCount.replace(",", "")
searchResultCount = int(searchResultCount)
if searchResultCount == 0:
return True, url, searchResultCount
r = np.min([math.ceil(searchResultCount / 50), acm_maxpage])
if (r > acm_maxpage):
print_debug(f'Warning: Too many results for ACM search: {"".join(infos["Keyword"])}, only downloading the first {acm_maxpage} pages', 0)
return False, url, searchResultCount
# Loop through all pages and save resulting bib files
for i in tqdm.tqdm(range(r), desc="pages"):
toOpen = url + str(i)
success, count = loadACMBib(toOpen, driver)
if success and (count > 0):
time.sleep(1)
#try:
tmpFile = ""
while True:
# If more than one bib element is in the file
if os.path.isfile(f'{outputFolderBib}acm.bib'):
tmpFile = f'{outputFolderBib}acm.bib'
break
# IF only one element is in the file
filesAvailable = glob.glob(f'{outputFolderBib}/acm_*.*.bib')
if (len(filesAvailable) == 1):
tmpFile = filesAvailable[0]
break
elif (len(filesAvailable) > 2):
print_debug(f'Error: Too many ACM files in {outputFolderBib}', 0)
break
time.sleep(1)
print_debug(f'Wait for file ACM bib file.', 2)
os.rename(tmpFile, getFileNameOutput(infos, outputFolderBib, i))
else:
return False, url, searchResultCount
return True, url, searchResultCount
def getURLIEEE(infos):
"""
Get the URL for the IEEE search
Attributes
----------
infos : dict
The information about the search
Returns
-------
str
The URL for the search
"""
concatentation="AND"
URL = ""
search = ""
titAbsDict = {SearchWhere.Title: "Document%20Title", SearchWhere.Abstract: "Abstract"}
key = ""
if (infos["SearchWhere"] == SearchWhere.TitleAbstract):
lstWhere = [SearchWhere.Title, SearchWhere.Abstract]
key = '('
for i, keyword in enumerate(infos["Keyword"]):
key = key + '('
for j, w in enumerate(lstWhere):
key = f'{key}"{titAbsDict[w]}":"{keyword}"'
if (len(lstWhere) - j > 1):
key = key + ' OR '
key = key + ')'
if (len(infos["Keyword"]) - i > 1):
key = key + ' AND '
key = key + ')'
elif infos["SearchWhere"] == SearchWhere.Text:# | _:
for i, keyword in enumerate(infos["Keyword"]):
key += f"%22{keyword}%22"
if (i < len(infos["Keyword"])-1):
key += f"+{concatentation}+"
else:
key += "("
for i, keyword in enumerate(infos["Keyword"]):
key += f'"{titAbsDict[searchWhere]}":"{keyword}"'
if (i < len(infos["Keyword"])-1):
key += "+AND+"
else:
key += ")"
search = key.replace("\"","%22").replace(" ","%20")
# The url must end with the page number so we can attach the page number later
url = f"https://ieeexplore.ieee.org/search/searchresult.jsp?action=search&matchBoolean=true"
url = url + f"&queryText={search}&highlight=true&returnFacets=ALL"
url = url + f'&returnType=SEARCH&matchPubs=true&ranges={infos["YearStart"]}_{infos["YearEnd"]}_Year'
url = url + f"&rowsPerPage=50&pageNumber="
return url
def loadIEEEBib (toOpen, driver, outputFolderBib):
"""
Load the IEEE bib file
Attributes
----------
toOpen : str
The URL to open
driver : selenium.webdriver
The selenium driver
outputFolderBib : str
The output folder for the bib file
Returns
-------
bool
True if the bib file was loaded
str
The path to the downloaded bib file
Empy if the file was not downloaded
"""
driver.get(toOpen)
## Check if login is needed - might not be needed
# lstLogin = driver.find_elements(by=By.TAG_NAME, value="xpl-personal-signin-custom")
# if len(lstLogin) > 0:
# print_debug("Performing Login")
# login = lstLogin[0]
# for elementInput in login.find_elements(by=By.TAG_NAME, value="input"):
# if "email" in elementInput.get_attribute("aria-label"):
# elementInput.send_keys(ieeeLoginEmail);
# # print_debug("email")
# elif "password" in elementInput.get_attribute("aria-label"):
# elementInput.send_keys(ieeeLoginPassword);
# # print_debug("password")
# for elementButton in login.find_elements(by=By.TAG_NAME, value="button"):
# if elementButton.text == "Sign In":
# elementButton.click()
time.sleep(random.uniform(5,20))
#Click SELECT ALL to export all papers
found = False
for e in driver.find_elements(by=By.CLASS_NAME, value="results-actions-selectall"):
if e.text == 'Select All on Page':
found = True
e.click()
if not found:
print_debug("Warning: element not found 'Select All on Page'", 2)
return False, ""
time.sleep(5)
# Find EXPORT and open the overlay
found = False
for e in driver.find_elements(by=By.CLASS_NAME, value="xpl-toggle-btn"):
if e.text == "Export":
found = True
e.click()
break
if not found:
print_debug("Warning: element not found 'Select All on Page'", 2)
return False, ""
time.sleep(random.uniform(2,7))
# Press "Cistion" in the Overlay
elementOverlay = driver.find_elements(by=By.CLASS_NAME, value="modal-content")
if (len(elementOverlay) != 1):
print_debug("Warning: element not found Citation Overlay", 2)
return False, ""
else:
elementOverlay = elementOverlay[0]
found = False
for e in elementOverlay.find_elements(by=By.CLASS_NAME, value="nav-item"):
if e.text == "Citations":
found = True
e.click()
break
if not found:
print_debug("Warning: element not found 'Citations'", 2)
return False, ""
time.sleep(random.uniform(2,5))
found = False
for e in elementOverlay.find_elements(by=By.TAG_NAME, value="label"):
if e.get_attribute("for") == "download-bibtex":
found = True
elementRadio = e.find_elements(by=By.TAG_NAME, value="input")
if len(elementRadio) != 1:
print_debug("Warning: element not found Dowload Bibtex", 2)
return False, ""
else:
elementRadio = elementRadio[0]
elementRadio.click()
break
if not found:
print_debug("Warning: element not found 'BibTeX'", 2)
return False, ""
time.sleep(random.uniform(2,3))
found = False
for e in elementOverlay.find_elements(by=By.TAG_NAME, value="label"):
if e.get_attribute("for") == "citation-abstract":
found = True
elementRadio = e.find_elements(by=By.TAG_NAME, value="input")
if len(elementRadio) != 1:
print_debug("Warning: element not found Citation Format", 2)
return False, ""
else:
elementRadio = elementRadio[0]
elementRadio.click()
break
if not found:
print_debug("Warning: element not found 'Citation and Abstract'", 2)
return False, ""
time.sleep(random.uniform(2,3))
# Press Downloadbutton
found = False
for e in elementOverlay.find_elements(by=By.TAG_NAME, value="button"):
if e.text == "Download":
found = True
e.click()
break
if not found:
print_debug("Warning: element not found 'Download'", 2)
return False, ""
time.sleep(random.uniform(3,7))
## test to get the file name from the download manager
# if(len(driver.window_handles) == 1):
# driver.execute_script("window.open('');")
# driver.switch_to.window(driver.window_handles[1])
# time.sleep(1)
# driver.get("chrome://downloads/")
# else:
# driver.switch_to.window(driver.window_handles[1])
# time.sleep(1)
# # https://stackoverflow.com/questions/61067252/navigating-chrome-downloads-page-using-python-selenium
# file_name = driver.execute_script("""
# var file_name = document.querySelector('downloads-manager')
# .shadowRoot.getElementById('frb0')
# .shadowRoot.getElementById('file-link').textContent;
# return file_name;
# """)
# driver.switch_to.window(driver.window_handles[0])
# pathToDownloadedFile = f'{outputFolderBib}{file_name}'
lstFiles = glob.glob(f'{outputFolderBib}/IEEE Xplore Citation BibTeX Download*.bib')
if len(lstFiles) != 1:
print_debug("Error: Too many IEEE Explore files in the Download folder, remove old ones before proceeding.", 1)
return False, ""
pathToDownloadedFile = lstFiles[0]
return True, pathToDownloadedFile
def saveIEEEBib(driver, infos, outputFolderBib):
ieee_maxpage = math.inf
print_debug(f'Search for: {infos["Keyword"]}', 1)
url = getURLIEEE(infos)
print_debug(url)
driver.get(url)
time.sleep(7)
save_screenshot(driver, infos)
searchResultCount = -1
successElement, element = getElement(driver, by=By.CLASS_NAME, value="Dashboard-header", number=0)
if (successElement):
successElement, element = getElement(element, by=By.TAG_NAME, value="span", number=0)
if (successElement):
if (element.text == "No results found"):
searchResultCount = 0
else:
successElement, element = getElement(element, by=By.TAG_NAME, value="span", number=1)
if successElement:
searchResultCount = int(element.text)
else:
return False, url, searchResultCount
else:
return False, url, searchResultCount
else:
return False, url, searchResultCount
if searchResultCount == 0:
return True, url, searchResultCount
r = int(np.min([math.ceil(searchResultCount / 50), ieee_maxpage]))
return True, url, searchResultCount
for i in tqdm.tqdm(range(r), desc="pages"):
toOpen = url + str(i+1)
success, pathToDownloadedFile = loadIEEEBib(toOpen, driver, outputFolderBib)
if success:
os.rename(pathToDownloadedFile, getFileNameOutput(infos, outputFolderBib, i))
else:
return False, url, searchResultCount
time.sleep(2)
return True, url, searchResultCount
def getURLScienceDirect(infos):
"""
Get the URL for the ScienceDirect search
Attributes
----------
infos : dict
The information about the search
"""
concatentation="AND"
search = ""
titleSearch = "tak="
if infos["SearchWhere"] == SearchWhere.Title:
titleSearch = "title="
elif infos["SearchWhere"] == SearchWhere.TitleAbstract:
titleSearch = "tak="
for i, keyword in enumerate(infos["Keyword"]):
search += f"%22{keyword}%22"
if (i < len(infos["Keyword"])-1):
search += f"%20{concatentation}%20"
url = f'https://www.sciencedirect.com/search?date={infos["YearStart"]}-{infos["YearEnd"]}&'
url = url+ f'{titleSearch}{search}&show=50&offset='
return url
def loginScienceDirect(driver, username, password):
Login_URL = "https://www.sciencedirect.com/"
driver.get(Login_URL)
time.sleep(5)
if DEBUG > 1:
driver.save_screenshot("./screenshots/init.png")
driver.find_element(by=By.LINK_TEXT, value="Sign in").click()
time.sleep(10)
mail = driver.find_element(by=By.ID, value="bdd-email")
mail.send_keys(username)
time.sleep(1)
mail.send_keys(Keys.ENTER)
time.sleep(1)
if DEBUG > 1:
driver.save_screenshot("./screenshots/login.png")
time.sleep(1)
driver.find_element(by=By.ID, value="bdd-elsPrimaryBtn").click()
time.sleep(1)
driver.find_element(by=By.ID, value="username").send_keys(username)
time.sleep(1)
pwd = driver.find_element(by=By.ID, value="password")
pwd.send_keys(password)
time.sleep(1)
pwd.send_keys(Keys.ENTER)
time.sleep(2)
try:
driver.find_element(by=By.ID, value="institution-button").click()
except:
print_debug("Error: intitution button apparently no accessable", 0)
driver.save_screenshot("./screenshots/StaleElement.png")
driver.find_element(by=By.ID, value="institution-button").click()
time.sleep(2)
return driver
def loadScienceDirectBib(toOpen, driver):
driver.get(toOpen)
time.sleep(5)
if DEBUG > 1: driver.save_screenshot("./screenshots/sciencedirect.png")
driver.find_element(by=By.ID, value="select-all-results").click()
time.sleep(1)
if DEBUG > 1: driver.save_screenshot("./screenshots/sciencedirect_clickall.png")
driver.find_element(by=By.CLASS_NAME, value="button-link.export-all-link-button.button-link-primary").click()
time.sleep(5)
driver.find_elements(by=By.CLASS_NAME, value="button-link.button-link-primary.export-option.u-display-block")[2].click()
time.sleep(10)
return True
def saveScienceDirectBib(driver, infos, outputFolderBib): #keywords_list, outputFolderBib, titleOnly):
sd_maxpage = 19
#driver = setupCrawler(outputFolderBib, Library.ScienceDirect)
url = getURLScienceDirect(infos)
driver.get("https://www.sciencedirect.com/")
save_screenshot(driver, infos)
try:
driver = loginScienceDirect(driver)
except NoSuchElementException:
print_debug("Already logged in or wrong credentials", 1)
# loginScienceDirect(driver)
save_screenshot(driver, infos)
# for keywords in keywords_list:
print_debug(f'Search for: {infos["Keyword"]}', 1)
url = getURLScienceDirect(infos)
driver.get(url)
time.sleep(3)
try:
searchResultCount = driver.find_element(by=By.CLASS_NAME, value="search-body-results-text")
searchResultCount = searchResultCount.text.split(" ")[0]
if "," in searchResultCount:
searchResultCount = searchResultCount.replace(",", "")
searchResultCount = int(searchResultCount)
except NoSuchElementException:
searchResultCount = 0
r = np.min([math.ceil(searchResultCount / 50), sd_maxpage])
if (r > sd_maxpage):
print_debug(f'Warning: Too many results for ScienceDirect search: {"".join(infos["Keyword"])}, only downloading the first {sd_maxpage} pages', 0)
return False, url, searchResultCount
for i in tqdm.tqdm(range(r), desc="pages"):
# driver = setupCrawler(dl_folder)
toOpen = url + str(i*50)
success = loadScienceDirectBib(toOpen, driver)
if not success:
return False, url, searchResultCount
return True, url, searchResultCount
def setupCrawler(targetLibrary, outputFolderBib):
"""
Setup the crawler for the target library and return the scelenium driver object
Attributes
----------
targetLibrary : Library Emum
The target library to crawl
outputFolderBib : str
The output folder for the bib files
"""
options = webdriver.ChromeOptions()
options.add_argument('window-size=1920,1080')
if targetLibrary == Library.ACM:
options.add_argument('headless')
options.add_argument("disable-gpu")
elif targetLibrary == Library.IEEE:
options.add_argument('headless')
options.add_argument("disable-gpu")
elif targetLibrary == Library.ScienceDirect:
None
p = {"download.default_directory": outputFolderBib}
options.add_experimental_option("prefs", p)
#ser = Service("./chromedriver.exe")
op = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options) #
print_debug("Driver setup complete.", 1)
return driver
def crawl(infos, outputFolderBib):
"""
Crawl the target library and save the bib file
Attributes
----------
infos : dict
The information about the search
outputFolderBib : str
The output folder for the bib file
"""
global globalLastLibrary
global driver
if (globalLastLibrary != infos["Library"]):
driver = setupCrawler(infos["Library"], outputFolderBib)
globalLastLibrary = infos["Library"]
print_debug(f'Setup Crwaler for {infos["Library"]}', 1)
print_debug(f'Start crawling {infos["Library"]}', 1)
if infos["Library"] == Library.ACM:
success, url, searchResultCount = saveACMBib(driver, infos, outputFolderBib)
elif infos["Library"] == Library.IEEE:
success, url, searchResultCount = saveIEEEBib(driver, infos, outputFolderBib)
elif infos["Library"] == Library.ScienceDirect:
keyword = [item.replace(" ", "%20") for item in keyword]
success, url, searchResultCount = saveScienceDirectBib(driver, infos, outputFolderBib)
else:
print_debug(f'Error: Library {infos["Library"]} not yet supported', 0)
return success, url, searchResultCount