├── .gitignore ├── .idea ├── CheggDownloader.iml ├── inspectionProfiles │ └── Project_Default.xml ├── misc.xml └── modules.xml ├── BookExporter.py ├── CheggDownloader.py ├── LICENSE ├── README.md └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Virtualenv 2 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ 3 | .Python 4 | [Bb]in 5 | [Ii]nclude 6 | [Ll]ib 7 | [Ll]ib64 8 | [Ll]ocal 9 | [Ss]cripts 10 | pyvenv.cfg 11 | .venv 12 | pip-selfcheck.json 13 | 14 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 15 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 16 | 17 | # User-specific stuff: 18 | .idea/**/workspace.xml 19 | .idea/**/tasks.xml 20 | .idea/dictionaries 21 | 22 | # Sensitive or high-churn files: 23 | .idea/**/dataSources/ 24 | .idea/**/dataSources.ids 25 | .idea/**/dataSources.xml 26 | .idea/**/dataSources.local.xml 27 | .idea/**/sqlDataSources.xml 28 | .idea/**/dynamic.xml 29 | .idea/**/uiDesigner.xml 30 | 31 | # Gradle: 32 | .idea/**/gradle.xml 33 | .idea/**/libraries 34 | 35 | # CMake 36 | cmake-build-debug/ 37 | 38 | # Mongo Explorer plugin: 39 | .idea/**/mongoSettings.xml 40 | 41 | ## File-based project format: 42 | *.iws 43 | 44 | ## Plugin-specific files: 45 | 46 | # IntelliJ 47 | out/ 48 | 49 | # mpeltonen/sbt-idea plugin 50 | .idea_modules/ 51 | 52 | # JIRA plugin 53 | atlassian-ide-plugin.xml 54 | 55 | # Cursive Clojure plugin 56 | .idea/replstate.xml 57 | 58 | # Crashlytics plugin (for Android Studio and IntelliJ) 59 | com_crashlytics_export_strings.xml 60 | crashlytics.properties 61 | crashlytics-build.properties 62 | fabric.properties 63 | -------------------------------------------------------------------------------- /.idea/CheggDownloader.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 11 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /BookExporter.py: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | 3 | import argparse 4 | import os 5 | import glob 6 | import json 7 | import shutil 8 | import urllib.parse 9 | import re 10 | import bs4 as bs 11 | import subprocess 12 | 13 | def get_path(url: str): 14 | urlpath = urllib.parse.urlparse(url).path 15 | match = re.search(r"^(/books/\d+)?/(.+?)(/content|/encrypted/\d+)?$", urlpath) 16 | path = match.group(2) 17 | if path[-8:].find(".") == -1: 18 | if str(match.group(3)).find("encrypted") >= 0: 19 | path += ".jpg" 20 | else: 21 | path += ".html" 22 | return path 23 | 24 | def export(dir, book_name, tmp_dir, out_dir): 25 | pages = [] 26 | 27 | pages_files = glob.glob(os.path.join(dir, '*_pages.json'))[0] 28 | with open(pages_files) as f: 29 | pages = json.load(f) 30 | 31 | if len(pages) == 0: 32 | return 33 | 34 | print("Copying files") 35 | if os.path.isdir(tmp_dir): 36 | shutil.rmtree(tmp_dir) 37 | shutil.copytree(dir, tmp_dir) 38 | 39 | filelist = [] 40 | pageimages = [] 41 | with open(os.path.join(tmp_dir, 'renames.json')) as f: 42 | renames = json.load(f) 43 | 44 | print("Fixing files") 45 | for page in pages: 46 | path = get_path(page["absoluteURL"]) 47 | changed = False 48 | file = os.path.join(tmp_dir, path) 49 | with open(file) as f: 50 | soup = bs.BeautifulSoup(f.read(), 'html.parser') 51 | for style in soup.head.find_all("style"): 52 | # some xhtml files contain "body{visibility:hidden}" making content invisible 53 | if style.string.find("visibility:hidden") != -1: 54 | style.decompose() 55 | changed = True 56 | 57 | for link in soup.find_all("link", href=True): 58 | if link["href"][0] == "/": 59 | new_path = get_path(link["href"]) 60 | link["href"] = os.path.relpath(os.path.join(tmp_dir, new_path), os.path.dirname(file)) 61 | changed = True 62 | 63 | for source in soup.find_all(["img", "script"], src=True): 64 | if source["src"][0] == "/": 65 | new_path = get_path(source["src"]) 66 | if new_path in renames: 67 | new_path = renames[new_path] 68 | source["src"] = os.path.relpath(os.path.join(tmp_dir, new_path), os.path.dirname(file)) 69 | changed = True 70 | if source.has_attr("id") and source["id"] == "pbk-page": 71 | pageimages.append(os.path.join(os.path.dirname(file), source["src"])); 72 | 73 | if changed: 74 | with open(file, "wb") as f: 75 | f.write(str(soup).encode("utf-8")) 76 | 77 | filelist.append(file) 78 | 79 | if len(pageimages) > 0: 80 | filelist = pageimages 81 | 82 | create_pdf(out_dir, book_name, filelist) 83 | 84 | def create_pdf(out_dir, book_name, filelist): 85 | print("Generating PDF, Please Wait! This will take a while.") 86 | 87 | outfile = os.path.join(out_dir, book_name + ".pdf") 88 | 89 | if filelist[0][-4:] == 'html': 90 | params = ["--no-pdf-compression", "--disable-javascript"] 91 | args = ["wkhtmltopdf"] 92 | else: 93 | params = [] 94 | args = ["magick"] 95 | 96 | args = args + params + filelist + [outfile] 97 | 98 | result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 99 | print("Created {:s}".format(outfile)) 100 | if result.returncode != 0: 101 | print(result.stderr) 102 | print("Warning! There was some error while creating PDF!") 103 | 104 | 105 | 106 | def main(): 107 | parser = argparse.ArgumentParser() 108 | parser.add_argument('dir', type=str, 109 | help='path to a location of book') 110 | 111 | parser.add_argument('--book-name', type=str, default='Book', 112 | help='name of the book. Default=[%(default)s]') 113 | parser.add_argument('--tmp-dir', type=str, default='tmp', 114 | help='specify a directory to keep temporally files. Default=[%(default)s]') 115 | parser.add_argument('--out-dir', type=str, default='.', 116 | help='specify a directory where to save exported book. Default=[Current Directory]') 117 | 118 | args = parser.parse_args() 119 | 120 | try: 121 | os.makedirs(args.out_dir, exist_ok=True) 122 | except OSError as e: 123 | print("Unable to create output directory {:s}: {:s}" 124 | .format(args.out_dir, e)) 125 | 126 | if not os.path.isdir(args.dir): 127 | print("Wrong location to book!") 128 | return 129 | 130 | export(args.dir, args.book_name, args.tmp_dir, args.out_dir) 131 | 132 | if __name__ == '__main__': 133 | main() 134 | -------------------------------------------------------------------------------- /CheggDownloader.py: -------------------------------------------------------------------------------- 1 | import bs4 as bs 2 | import argparse 3 | import browser_cookie3 as cookies 4 | import os 5 | import requests 6 | import time 7 | import sys 8 | import webbrowser 9 | import json 10 | import re 11 | import urllib.parse 12 | import cgi 13 | 14 | BASE_URL = "https://jigsaw.chegg.com" 15 | API_URL = BASE_URL + "/api/v0" 16 | HTML_HEADERS = { 17 | 'upgrade-insecure-requests': "1", 18 | 'user-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) " 19 | "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36", 20 | 'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", 21 | 'dnt': "1", 22 | 'referer': "https://ereader.chegg.com/", 23 | 'accept-encoding': "gzip, deflate, br", 24 | 'accept-language': "en", 25 | 'cache-control': "no-cache", 26 | 'X-Requested-With': 'XMLHttpRequest' 27 | } 28 | IMAGE_HEADERS = { 29 | 'user-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) " 30 | "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36", 31 | 'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", 32 | 'dnt': "1", 33 | 'accept-encoding': "gzip, deflate, br", 34 | 'accept-language': "en", 35 | 'cache-control': "no-cache", 36 | } 37 | 38 | JAR = {c.name: c.value for c in cookies.chrome(domain_name='jigsaw.chegg.com')} 39 | 40 | 41 | def prompt_login() -> None: 42 | choice = input( 43 | "It seems that you have not logged into the Chegg eReader yet.\n" 44 | "You can also log in by copying a pasting the following URL into " 45 | "Google Chrome:\nhttps://ereader.chegg.com\n" 46 | "Would you like to open Google Chrome and log in? (Y/N) ") 47 | if choice.lower() == 'y': 48 | webbrowser.get('chrome').open('https://ereader.chegg.com') 49 | 50 | 51 | def get_response(url, querystring, max_retries, retry_delay) -> str: 52 | resp = None 53 | for i in range(0, max_retries): 54 | resp = requests.get(url, params=querystring, headers=HTML_HEADERS, cookies=JAR) 55 | if resp.status_code in [200, 401, 406]: # don't retry 56 | break 57 | print("[status={:d} attempt={:d}] Unable to download page {:s}: {:s}" 58 | .format(resp.status_code, i, url, str(resp.text))) 59 | time.sleep(retry_delay / 1000) 60 | if resp: 61 | return resp.text 62 | return "" 63 | 64 | def get_json_data(isbn: str, path: str, max_retries: int, retry_delay: int): 65 | url = API_URL + "/books/{:s}/{:s}".format(isbn, path) 66 | resp = get_response(url, {}, max_retries, retry_delay) 67 | if resp: 68 | return json.loads(resp) 69 | return None 70 | 71 | def get_pages(isbn: str, max_retries: int, retry_delay: int): 72 | return get_json_data(isbn, "pages", max_retries, retry_delay) 73 | 74 | def get_pagebreaks(isbn: str, max_retries: int, retry_delay: int): 75 | return get_json_data(isbn, "pagebreaks", max_retries, retry_delay) 76 | 77 | def get_toc(isbn: str, max_retries: int, retry_delay: int): 78 | return get_json_data(isbn, "toc", max_retries, retry_delay) 79 | 80 | def get_figures(isbn: str, max_retries: int, retry_delay: int): 81 | return get_json_data(isbn, "figures", max_retries, retry_delay) 82 | 83 | def get_ancillaries(isbn: str, max_retries: int, retry_delay: int): 84 | return get_json_data(isbn, "ancillaries", max_retries, retry_delay) 85 | 86 | def save_json_data(out_dir, name, data): 87 | with open(os.path.join(out_dir, "{:s}.json".format(name)), "w") as f: 88 | json.dump(data, f) 89 | 90 | def get_html(isbn: str, start: str, end: str, max_retries: int, retry_delay: int) -> str: 91 | url = API_URL + "/books/{:s}/print".format(isbn) 92 | querystring = {'from': start, 'to': end} 93 | return get_response(url, querystring, max_retries, retry_delay) 94 | 95 | def mark_renamed(source, target, out_dir): 96 | with open(os.path.join(out_dir, 'renames.json'), 'rb') as f: 97 | renames = json.load(f) 98 | 99 | prefixlen = len(os.path.abspath(out_dir)) 100 | abssource = os.path.abspath(source) 101 | renames[abssource[prefixlen+1:]] = os.path.abspath(target)[prefixlen+1:] 102 | save_json_data(out_dir, "renames", renames) 103 | 104 | def download_image(url: str, path: str, out_dir: str, max_retries: int, retry_delay: int, rename: bool) -> bool: 105 | new_filename = None 106 | success = False 107 | with open(path, 'wb') as f: 108 | resp = None 109 | for i in range(0, max_retries): 110 | resp = requests.get(url, headers=IMAGE_HEADERS, cookies=JAR, stream=True) 111 | if resp.status_code == 200: 112 | if 'Content-Disposition' in resp.headers: 113 | value, params = cgi.parse_header(resp.headers['Content-Disposition']) 114 | if params['filename'] != os.path.basename(path): 115 | new_filename = os.path.join(os.path.dirname(path), params['filename']) 116 | if os.path.isfile(new_filename): 117 | print("File '{:s}' already exists, skipping download!".format(new_filename)) 118 | mark_renamed(path, new_filename, out_dir) 119 | f.close() 120 | os.remove(path) 121 | return True 122 | break 123 | print("[status={:d} attempt={:d}] Unable to download {:s}: {:s}" 124 | .format(resp.status_code, i, url, str(resp.text))) 125 | time.sleep(retry_delay / 1000) 126 | if resp: 127 | for chunk in resp.iter_content(chunk_size=1024): 128 | f.write(chunk) 129 | success = True 130 | 131 | if success: 132 | if new_filename: 133 | mark_renamed(path, new_filename, out_dir) 134 | if rename: 135 | os.rename(path, new_filename) 136 | else: 137 | os.remove(path) 138 | 139 | return success 140 | 141 | def get_image(src: str, out_file: str, out_dir: str, max_retries: int, retry_delay: int) -> bool: 142 | url = API_URL + src 143 | return download_image(url, out_file, out_dir, max_retries, retry_delay, False) 144 | 145 | def get_filename(book_name: str, page_num: str, out_dir: str) -> str: 146 | filename = '{:s}_{:s}.png'.format(book_name, page_num) 147 | return os.path.join(out_dir, filename) 148 | 149 | def get_path(url: str): 150 | urlpath = urllib.parse.urlparse(url).path 151 | match = re.search(r"^(/books/\d+)?/(.+?)(/content|/encrypted/\d+)?$", urlpath) 152 | path = match.group(2) 153 | if path[-8:].find(".") == -1: 154 | if str(match.group(3)).find("encrypted") >= 0: 155 | path += ".jpg" 156 | else: 157 | path += ".html" 158 | return path 159 | 160 | def save_file(url: str, out_dir: str, cache: bool, callback) -> bool: 161 | if url[0:2] == "//": 162 | url = "https:" + url 163 | elif url[0] == "/": 164 | url = BASE_URL + url 165 | 166 | base_path = get_path(url) 167 | path = os.path.join(out_dir, base_path) 168 | os.makedirs(os.path.dirname(path), exist_ok=True) 169 | if cache and os.path.isfile(path): 170 | print("File '{:s}' already exists, skipping download!".format(base_path)) 171 | return True 172 | 173 | return callback(url, path) 174 | 175 | def download_files(html: str, baseurl: str, out_dir: str, 176 | max_retries: int, retry_delay: int) -> bool: 177 | soup = bs.BeautifulSoup(html, 'html.parser') 178 | files = [t['href'] for t in soup.find_all('link', href=True)] 179 | files += [t['src'] for t in soup.find_all('img', src=True)] 180 | files += [t['src'] for t in soup.find_all('script', src=True)] 181 | # we should process 'style' too for CSS urls 182 | 183 | result = True 184 | for offset, src in enumerate(files): 185 | if src[0:4] != 'http' and src[0:1] != "/": 186 | src = baseurl + '/' + src 187 | print("Downloading file '{:s}' ({:d}/{:d})".format(src, offset + 1, len(files))) 188 | # if it's a CSS file we actually should process it too for urls 189 | if not save_file(src, out_dir, True, lambda url, path: download_image(url, path, out_dir, max_retries, retry_delay, True)): 190 | result = False 191 | return result 192 | 193 | def download_images(html: str, page: str, 194 | book_name: str, out_dir: str, 195 | max_retries: int, retry_delay: int) -> bool: 196 | soup = bs.BeautifulSoup(html, 'html.parser') 197 | images = [t['src'] for t in soup.find_all('img')] 198 | result = True 199 | for offset, src in enumerate(images): 200 | name = page 201 | if offset != 0: 202 | name = name + "_" + str(offset) 203 | if not get_image(src, get_filename(book_name, name, out_dir), out_dir, max_retries, retry_delay): 204 | result = False 205 | return result 206 | 207 | 208 | def download_single(isbn: str, page: str, 209 | book_name: str, out_dir: str, 210 | max_retries: int, retry_delay: int) -> bool: 211 | html = get_html(isbn, page, page, max_retries, retry_delay) 212 | soup = bs.BeautifulSoup(html, 'html.parser') 213 | images = [t['src'] for t in soup.find_all('img')] 214 | if images: 215 | if not get_image(images[0], get_filename(book_name, page, out_dir), out_dir, max_retries, retry_delay): 216 | return False 217 | return True 218 | return False 219 | 220 | 221 | def download_list(isbn: str, pages: list, 222 | book_name: str, out_dir: str, 223 | max_retries: int, retry_delay: int, 224 | quiet: bool=False) -> None: 225 | save_json_data(out_dir, "renames", {}) 226 | failed_pages = [] 227 | start_time = time.time() 228 | for page in pages: 229 | if not quiet: 230 | print("downloading page {:s}".format(page)) 231 | if not download_single(isbn, str(page), book_name, out_dir, max_retries, retry_delay): 232 | failed_pages.append(page) 233 | end_time = time.time() 234 | print("downloaded {:d} pages in {:6.3f} seconds" 235 | .format(len(pages) - len(failed_pages) + 1, end_time - start_time)) 236 | if failed_pages: 237 | print("failed pages: {:s}".format(str(failed_pages))) 238 | 239 | 240 | def download_range(isbn: str, start: int, end: int, interval: int, 241 | book_name: str, out_dir: str, 242 | max_retries: int, retry_delay: int, 243 | quiet: bool=False) -> None: 244 | save_json_data(out_dir, "renames", {}) 245 | failed_pages = [] 246 | start_time = time.time() 247 | for page in range(start, end, interval): 248 | html = get_html(isbn, str(page), str(page + interval - 1), max_retries, retry_delay) 249 | if not quiet: 250 | print("downloading page {:d}/{:d}".format(page, end)) 251 | result = download_images(html, str(page), book_name, out_dir, max_retries, retry_delay) 252 | if not result: 253 | failed_pages.append(page + offset) 254 | end_time = time.time() 255 | print("downloaded {:d} pages in {:6.3f} seconds" 256 | .format((end - start) - len(failed_pages) + 1, end_time - start_time)) 257 | if failed_pages: 258 | print("failed pages: {:s}".format(str(failed_pages))) 259 | 260 | def download_figures(figures, out_dir, max_retries, retry_delay): 261 | for i, figure in enumerate(figures): 262 | print("Downloading figure '{:s}' ({:d}/{:d})".format(str(figure["title"]), i + 1, len(figures))) 263 | if not save_file(figure["imageURL"], out_dir, True, lambda url, path: download_image(url, path, out_dir, max_retries, retry_delay, True)): 264 | break 265 | 266 | 267 | def download_all(isbn: str, quality: int, book_name: str, out_dir: str, 268 | max_retries: int, retry_delay: int, 269 | quiet: bool=False) -> None: 270 | failed_pages = [] 271 | start_time = time.time() 272 | 273 | pages = get_pages(isbn, max_retries, retry_delay) 274 | if not pages: 275 | print('You need to login!') 276 | return False 277 | 278 | save_json_data(out_dir, "renames", {}) 279 | 280 | save_json_data(out_dir, book_name + "_pages", pages) 281 | 282 | pagebreaks = get_pagebreaks(isbn, max_retries, retry_delay) 283 | save_json_data(out_dir, book_name + "_pagebreaks", pagebreaks) 284 | 285 | toc = get_toc(isbn, max_retries, retry_delay) 286 | save_json_data(out_dir, book_name + "_toc", toc) 287 | 288 | figures = get_figures(isbn, max_retries, retry_delay) 289 | save_json_data(out_dir, book_name + "_figures", figures) 290 | 291 | ancillaries = get_ancillaries(isbn, max_retries, retry_delay) 292 | save_json_data(out_dir, book_name + "_ancillaries", ancillaries) 293 | 294 | downloaded_urls = [] 295 | 296 | download_figures(figures, out_dir, max_retries, retry_delay) 297 | 298 | for i, page in enumerate(pages): 299 | label = "" 300 | if "page" in page: 301 | label = page["page"] 302 | elif "number" in page: 303 | label = str(page["number"]) 304 | elif "chapterTitle" in page: 305 | label = page["chapterTitle"] 306 | 307 | if not quiet: 308 | print("downloading page {:s} ({:d}/{:d})".format(label, i + 1, len(pages))) 309 | 310 | def page_saver(url, path): 311 | if url in downloaded_urls: 312 | return True 313 | 314 | html = get_response(url, {}, max_retries, retry_delay) 315 | if html.find('popup-signin') != -1: 316 | print('You need to login!') 317 | return False 318 | 319 | downloaded_urls.append(url) 320 | with open(path, "wb") as f: 321 | f.write(html.encode("utf-8")) 322 | 323 | urlparts = list(urllib.parse.urlsplit(url)) 324 | urlparts[2] = os.path.dirname(urlparts[2]) 325 | urlparts[3] = '' 326 | urlparts[4] = '' 327 | if not download_files(html, urllib.parse.urlunsplit(urlparts), out_dir, max_retries, retry_delay): 328 | failed_pages.append(url) 329 | return True 330 | 331 | if not save_file("{:s}?width={:d}".format(page["absoluteURL"], quality), out_dir, False, lambda url, path: page_saver(url, path)): 332 | break 333 | 334 | end_time = time.time() 335 | print("downloaded {:d} pages in {:6.3f} seconds" 336 | .format(len(pages) - len(failed_pages) + 1, end_time - start_time)) 337 | if failed_pages: 338 | print("failed pages: {:s}".format(str(failed_pages))) 339 | 340 | 341 | def verify_args(args): 342 | if not args.start and not args.end and not args.pages: 343 | print("Fatal: you must either specify a range or a list of pages") 344 | sys.exit(-1) 345 | 346 | 347 | def main(): 348 | parser = argparse.ArgumentParser() 349 | parser.add_argument('isbn', type=str, 350 | help='the e-ISBN of the book to download') 351 | 352 | page_group = parser.add_argument_group('pages') 353 | page_group.add_argument('start', type=int, nargs='?', 354 | help='starting page to download') 355 | page_group.add_argument('end', type=int, nargs='?', 356 | help='ending page to download') 357 | page_group.add_argument('-i', '--interval', type=int, default=2, 358 | help='maximum pages to query and download at once') 359 | page_group.add_argument('-p', '--pages', type=str, nargs='*', 360 | help='a list of pages to download, separated by space') 361 | 362 | error_group = parser.add_argument_group("error handling") 363 | error_group.add_argument('--max-retries', type=int, default=3, 364 | help='maximum number to retry downloading a page if it fails. Default=[%(default)d]') 365 | error_group.add_argument('--retry-delay', type=int, default=500, 366 | help='delay in milliseconds between retries. Default=[%(default)d]') 367 | 368 | parser.add_argument('--quality', type=int, default=2000, 369 | help='quality of the book to download. Default=[%(default)s]') 370 | parser.add_argument('--book-name', type=str, default='Book', 371 | help='name of the book to download. Default=[%(default)s]') 372 | parser.add_argument('--out-dir', type=str, default='.', 373 | help='specify a directory to save all images. Default=[Current Directory]') 374 | 375 | args = parser.parse_args() 376 | 377 | verify_args(args) 378 | 379 | if len(JAR) == 0: 380 | prompt_login() 381 | sys.exit(0) 382 | try: 383 | os.makedirs(args.out_dir, exist_ok=True) 384 | except OSError as e: 385 | print("Unable to create output directory {:s}: {:s}" 386 | .format(args.out_dir, e)) 387 | 388 | if args.pages: 389 | if 'all' in args.pages: 390 | download_all( 391 | args.isbn, 392 | args.quality, 393 | args.book_name, 394 | args.out_dir, 395 | args.max_retries, 396 | args.retry_delay, 397 | ) 398 | else: 399 | download_list( 400 | args.isbn, 401 | args.pages, 402 | args.book_name, 403 | args.out_dir, 404 | args.max_retries, 405 | args.retry_delay, 406 | ) 407 | else: 408 | download_range( 409 | args.isbn, 410 | args.start, 411 | args.end, 412 | args.interval, 413 | args.book_name, 414 | args.out_dir, 415 | args.max_retries, 416 | args.retry_delay, 417 | ) 418 | 419 | 420 | if __name__ == '__main__': 421 | main() 422 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## WARNING 2 | THIS TOOL IS NOT MEANT TO CIRCUMVENT COPYRIGHT PROTECTION. IT SHOULD ONLY BE USED TO DOWNLOAD ETEXTBOOKS THAT **YOU OWN**. REPRODUCING AND/OR DISTRIBUTING COPYRIGHTED WORK IS A CRIME IN MANY COUNTRIES AND JURISDICTIONS. 3 | 4 | CHEGG HAS UPDATED THEIR 14 DAY RETURN POLICY SO THAT THEY DO NOT HAVE TO GIVE YOU A REFUND IF YOU REACH THE MAXIMUM NUMBER OF PRINTED PAGES. PLEASE DO NOT ABUSE THEIR GENEROUS RETURN POLICY. 5 | 6 | # CheggDownloader 7 | This is a simple Python script that allows you to download an eTextbook from Chegg.com. Output (on the limited sample size that I have) will be stored as a separate PNG file for each page. 8 | 9 | ## Requirements 10 | 1. Python 3 11 | 2. Google Chrome 12 | 3. `browser_cookie3` 13 | 4. `requests` 14 | 5. The eTextbook you are downloading must allow itself to be printed (limited pages OK) 15 | 16 | ## Usage 17 | 1. Make sure that you have purchased the eTextbook from Chegg (they have a generous 14-day return policy). 18 | 2. **Using Chrome**, go to the eReader website (https://ereader.chegg.com) and log in. 19 | 3. Open the book you want to download. Record the e-ISBN number as shown in the URL. It should be the 13-digit number after `/books/`. 20 | 4. Click on the "Print" icon and record the maximum number of pages you are allowed to download at once (the larger the number, the faster the book can be downloaded). 21 | 5. Find the starting and ending page that you would like to download. 22 | 6. Start downloading 23 | ```bash 24 | $ pip install -r requirements.txt 25 | $ python3 CheggDownloader.py -i 26 | $ # Example 27 | $ python3 CheggDownloader.py 1234567890123 1 999 -i 5 28 | $ # Download to a specified folder (will be created is doesn't exist) 29 | $ python3 CheggDownloader.py 1234567890123 1 999 -i 5 --out-dir=book/ 30 | ``` 31 | 32 | ### Downloading unnumbered pages 33 | If some pages in the book are unnumbered, or are not numbered with Arabic numerals (e.g. numbered with Roman numerals), you may use 34 | ```bash 35 | $ python3 CheggDownloader.py -p 36 | $ # Example 37 | $ python3 CheggDownloader.py 1234567890123 -p i ii iii iv v 38 | ``` 39 | 40 | ## Options 41 | See the help message: `python3 CheggDownloader.py -h` 42 | ``` 43 | usage: CheggDownloader.py [-h] [-i INTERVAL] [-p [PAGES [PAGES ...]]] 44 | [--max-retries MAX_RETRIES] 45 | [--retry-delay RETRY_DELAY] [--book-name BOOK_NAME] 46 | [--out-dir OUT_DIR] 47 | isbn [start] [end] 48 | 49 | positional arguments: 50 | isbn the e-ISBN of the book to download 51 | 52 | optional arguments: 53 | -h, --help show this help message and exit 54 | --book-name BOOK_NAME 55 | name of the book to download. Default=[Book] 56 | --out-dir OUT_DIR specify a directory to save all images. 57 | Default=[Current Directory] 58 | 59 | pages: 60 | start starting page to download 61 | end ending page to download 62 | -i INTERVAL, --interval INTERVAL 63 | maximum pages to query and download at once 64 | -p [PAGES [PAGES ...]], --pages [PAGES [PAGES ...]] 65 | a list of pages to download, separated by space 66 | 67 | error handling: 68 | --max-retries MAX_RETRIES 69 | maximum number to retry downloading a page if it 70 | fails. Default=[3] 71 | --retry-delay RETRY_DELAY 72 | delay in milliseconds between retries. Default=[500] 73 | ``` 74 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4 2 | browser_cookie3 3 | requests --------------------------------------------------------------------------------