This repository has been archived by the owner on Jun 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpearson.py
169 lines (148 loc) · 7.4 KB
/
pearson.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
from selenium.webdriver.common.by import By
from seleniumwire import webdriver
import traceback
import aiofiles
import pathlib
import asyncio
import aiohttp
import shutil
import sys
import re
async def main():
global done
options = {'ignore_http_methods': ['HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE']}
if sys.platform.startswith("win"):
chromedriver = "chromedriver.exe"
else:
if shutil.which("chromedriver"):
chromedriver = "chromedriver"
else:
chromedriver = "./chromedriver"
driver = webdriver.Chrome(chromedriver, seleniumwire_options=options)
driver.set_page_load_timeout(120)
driver.set_script_timeout(120)
driver.get('https://www.pearson.it/')
while True:
input('Press [Enter] when you are on a page of the ebook (must be on the first tab!)...')
type = input("What type of ebook is this?\n"
"1) eText ISE\n"
"2) Reader+\n"
">>> ")
try:
if type == "1":
del driver.requests
try:
element = driver.find_element(By.CSS_SELECTOR, '.pageNavigation .pageNavigationContainer .nextPage .navigationBtn')
except Exception:
element = driver.find_element(By.CSS_SELECTOR, '.pageNavigation .pageNavigationContainer .previousPage .navigationBtn')
element.click()
driver.wait_for_request('/pages/*', timeout=30)
for request in driver.requests:
if "/eplayer/pdfassets/" in str(request.url) and "/pages/" in str(request.url):
template = request
break
async with aiohttp.ClientSession(headers=dict(template.headers),
connector=aiohttp.TCPConnector(limit=0)) as cs:
done = False
baseurl = template.url[:template.url.rfind("/")] + "/page"
async def fetch_page(number):
global done
if done:
return
retries = 0
while True:
try:
async with cs.get(f"{baseurl}{number}") as req:
if not req.ok:
done = True
return
async with aiofiles.open(f"./dump/pearson/etext-ise/{id}/{number}.png", 'wb') as f:
await f.write(await req.read())
print(f"Fetched page {number}!")
break
except Exception:
if retries > max_retries:
raise
retries += 1
continue
async def worker():
while not tasks.empty():
await tasks.get_nowait()
id = input("With what name should this book be saved?\n"
"(Leave empty to autodetect the id)\n"
">>> ") or re.match(".*/eplayer/pdfassets/.*/.*/(.*)/pages/.*", template.url)[1]
shutil.rmtree(f"./dump/pearson/etext-ise/{id}", ignore_errors=True)
pathlib.Path(f"./dump/pearson/etext-ise/{id}").mkdir(parents=True, exist_ok=True)
print(f"\nStarted dumping eText ISE book {id}...")
i = 0
amount = 25
max_retries = 3
while not done:
tasks = asyncio.Queue()
for x in range(i, i + amount):
tasks.put_nowait(fetch_page(x))
await asyncio.gather(*[worker() for _ in range(amount)])
i += amount
print(f"\nFinished dumping eText ISE book {id}!\n\n")
if type == "2":
del driver.requests
try:
element = driver.find_element(By.CSS_SELECTOR, '.pageNavigation .pageNavigationContainer .nextPage .navigationBtn')
except Exception:
element = driver.find_element(By.CSS_SELECTOR, '.pageNavigation .pageNavigationContainer .previousPage .navigationBtn')
element.click()
driver.wait_for_request('/pages/*', timeout=30)
for request in driver.requests:
if "/pages/page" in str(request.url):
template = request
break
async with aiohttp.ClientSession(headers=dict(template.headers),
connector=aiohttp.TCPConnector(limit=0)) as cs:
done = False
baseurl = template.url[:template.url.rfind("/")] + "/page"
async def fetch_page(number):
global done
if done:
return
retries = 0
while True:
try:
async with cs.get(f"{baseurl}{number}") as req:
if not req.ok:
done = True
return
async with aiofiles.open(f"./dump/pearson/reader-plus/{id}/{number}.png", 'wb') as f:
await f.write(await req.read())
print(f"Fetched page {number}!")
break
except Exception:
if retries > max_retries:
raise
retries += 1
continue
async def worker():
while not tasks.empty():
await tasks.get_nowait()
id = input("With what name should this book be saved?\n"
"(Leave empty to autodetect the id)\n"
">>> ") or re.match(".*/(.*?)/.*?/pages/.*", template.url)[1]
shutil.rmtree(f"./dump/pearson/reader-plus/{id}", ignore_errors=True)
pathlib.Path(f"./dump/pearson/reader-plus/{id}").mkdir(parents=True, exist_ok=True)
print(f"\nStarted dumping Reader+ book {id}...")
i = 0
amount = 25
max_retries = 3
while not done:
tasks = asyncio.Queue()
for x in range(i, i + amount):
tasks.put_nowait(fetch_page(x))
await asyncio.gather(*[worker() for _ in range(amount)])
i += amount
print(f"\nFinished dumping Reader+ book {id}!\n\n")
except Exception:
print("\n\nSomething went wrong!\n")
exc = "".join(traceback.format_exception(*sys.exc_info()))
print(exc)
print("\n")
if __name__ == "__main__":
asyncio.run(main())