Repository: t3nsor/quora-backup Branch: master Commit: 1032cbef56c6 Files: 5 Total size: 45.6 KB Directory structure: gitextract_bfuioo1s/ ├── .gitignore ├── LICENSE ├── README.md ├── converter.py └── crawler.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.swp ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. {signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: README.md ================================================ ## Installation You need Python 3, version 3.2 or higher, with the `html5lib` library installed. Pick up a copy [here](https://github.com/html5lib/html5lib-python). This software is only known to work on Linux. It can probably be made to work in Windows too, but I haven't tried it. Patches welcome. No installation is required, but make sure that `converter.py` and `crawler.py` are executable. (Or you can just run them by invoking `python3` explicitly.) ## Basic usage: downloading all your answers To view all your answers, go to the answers section of [Your Content](https://www.quora.com/content?content_types=answers) and scroll all the way down until there are no more answers to load. Type the following into your browser's URL bar: javascript:window.open().document.write(JSON.stringify(Array.prototype.map.call(document.querySelectorAll('.UserContentList .pagedlist_item'), function (e) { return [e.getElementsByTagName('a')[0].href, e.getElementsByClassName('metadata')[0].innerHTML] }))) **Note:** You can copy and paste the code above, but your browser might automatically remove the `javascript:` prefix from the URL when you do so. If that happens, you'll have to type in the `javascript:` part yourself. Alternatively, you can just use the browser console to execute the javascript code. (You need popups enabled in order for this to work. If your popup blocker blocks the window, disable it and try again.) This creates a popup window or new tab containing a list of your answers, in a format that looks something like this: `[["https://www.quora.com/Do-classical-mechanics-work-beyond-the-speed-of-light/answer/Brian-Bi","Added Fri"],["https://www.quora.com/Are-competitive-programmers-happy-when-working-as-software-engineers/answer/Brian-Bi","Added Thu"],["https://www.quora.com/How-did-Brian-Bi-not-know-it-was-Chinese-New-Year-today/answer/Brian-Bi","Added Thu"],["https://www.quora.com/How-many-hours-of-studies-did-Brian-Bi-put-in-per-day-in-order-to-prepare-for-the-IChO/answer/Brian-Bi","Added Thu"]`... Copy and paste the entire contents of the window or tab into a text editor and save it as a file, `answers.json`. Go back to your browser, type in the following URL, and press Enter: `javascript:window.open().document.write(new Date().valueOf() + '
' + new Date().getTimezoneOffset())` (The same caveats as before apply.) Again a new window or tab should pop up, showing the date in a numeric format, with two lines. The first line shows the current timestamp in numeric format. The second shows the offset of your time zone from UTC in minutes. Take note of both of these numbers. Suppose you installed the scripts in `/home/brian/quora-backup`. You can run the crawler as follows: `/home/brian/quora-backup/crawler.py answers.json /home/brian/quora-answers --origin_timestamp=${TIMESTAMP} --origin_timezone=${OFFSET}` replacing `${TIMESTAMP}` with the timestamp value previously obtained from the browser, and `${OFFSET}` with the time zone offset value. This creates a new directory, `/home/brian/quora-answers`, and populates it with the answers specified, after downloading them from Quora. It also generates a timestamp in YYYY-MM-DD format for each answer. ## Converting answers to a standalone format The converter can be run as follows: `/home/brian/quora-backup/converter.py /home/brian/quora-answers /home/brian/quora-answers-cooked` This creates the directory `/home/brian/quora-answers-cooked` and copies each answer downloaded into `/home/brian/quora-answers` into the new directory after processing it to remove everything other than the answer content itself. If this step succeeds, then the answer will still be readable even if Quora disappears from the face of the Web. ## What the crawler does The crawler is pretty simple: its job is to download the URLs you provide. But it also has a slightly nontrivial task, which is to determine the date on which each answer was written (give or take a day). This is done by reading the timestamps provided on the Your Content page itself. But the more recent timestamps given are relative, not absolute (for example, "Fri" if you wrote answer last Friday). That's why the crawler needs to be told at what time you accessed that page and in what time zone, so it can resolve those strings into absolute dates. ## What the converter does The converter has three main functions: 1. It removes everything on the page other than the answer content. No bar at the top, no sidebar with related answers, no box indicating why the answer was collapsed (if it was); your name is not shown, nor are upvotes, the timestamp, view count, comments, or the upvote and downvote buttons. All that's left is answer content. This also reduces the size of the HTML considerably. 2. It downloads a copy of each image embedded in your answer. These images are all hosted on Quora's servers; after running the converter, you'll have a copy on local disk, so you'll still be able to view the images even if Quora disappears. (This functionality can be disabled using the `-n` flag.) 3. It removes extraneous HTML elements and attributes, simplifying the HTML as much as possible. ## FAQ **Why did you write your own Quora backup tool when there are already a zillion of them?** Because I believe this tool is unique in that it allows you to reliably and easily download ALL your answers, even if you have thousands of them, AND to ensure that they still display properly even if Quora completely disappears. **What if I only want to download some of my answers?** To download only some of your answers, just remove all the entries from `answers.json` you don't want. If you also just want to download some recent answers, you don't have to scroll all the way down on the "Your Content" page. Yes, I realize this is really user-unfriendly. It would be nice to have a GUI. Patches welcome. **Won't Quora flag me for using a script to automatically download answers?** It depends on how many answers you're downloading. If it's less than a thousand, you'll probably be fine, but I take no responsibility if something bad happens to you. If you have a LOT of answers, you might want to take advantage of the built-in rate limiting options. Both the crawler and converter support a `--delay` flag; for example, `--delay=1` tells the script to pause for a second after every download. Don't ask me what value to use here; I don't know. Use this software at your own risk. **Why is this licensed under the GPL? I noticed you usually prefer more permissive licenses.** Because I want to make sure that all changes get merged back into my repository. There is a very good reason for this: there is only one Quora, and they'll probably change the way they generate HTML, which means this software will periodically stop working properly. I want to maintain a single version that's fully up to date with all the patches other people submit, rather than having multiple versions running around with patches for different kinds of elements. ## Errors and bugs A message starting with [FATAL] signals that the script cannot function at all. [ERROR] means that processing of a single answer was aborted due to an unrecoverable error; [WARNING] means an error condition arose which prevented some feature from working properly but did not abort the processing of an answer. If you run with the `-v` flag, you'll also see [DEBUG] messages. The converter will emit a [WARNING] message if it doesn't understand the HTML found in the answer. I have tested the converter against my entire set of answers, so I believe that as of the time of this release, this should never happen. But the format of Quora's HTML is likely to change in the future, which means the converter will stop working properly. If this happens, you're likely to see [WARNING] messages. Those should be reported. If you want to report such a bug in the converter, try re-running with the "-v" flag, and include with your report everything between the closest "Filename:" lines before and after the [WARNING] message. (This doesn't mean other kinds of bugs shouldn't be reported; I am just giving instructions on how to report the most common kind of bug I expect.) ================================================ FILE: converter.py ================================================ #!/usr/bin/env python3 import argparse import errno from html5lib import (HTMLParser, serializer, treebuilders, treewalkers) import os import re import sys import time import urllib.error import urllib.request from xml.dom.minidom import Node def log_if_v(msg): if args.verbose: print('[DEBUG] %s' % msg, file=sys.stderr) def get_title_node(document): for node in document.getElementsByTagName('title'): return node return None def get_text_content(node): text = '' for text_node in node.childNodes: if text_node.nodeType == Node.TEXT_NODE: text += text_node.data return text # The HTML can mostly be saved as-is. The main changes we want to make are: # 1) Remove most s and attributes since they are not needed anymore. # 2) Rewrite relative paths ("/Brian-Bi") to full URLs # 3) Download a copy of each embedded image def cleanup_tree(doc, src, dest): for child in src.childNodes: if child.nodeType == Node.TEXT_NODE: # Text nodes can simply be left as-is dest.appendChild(child.cloneNode(False)) continue if child.nodeType != Node.ELEMENT_NODE: # ??? raise ValueError() # Otherwise, it's an element node. if child.tagName in ['br', 'hr']: dest.appendChild(child.cloneNode(False)) elif child.tagName in ['b', 'i', 'u', 'h2', 'ol', 'ul', 'li', 'blockquote', 'wbr', 'p']: # This node doesn't need to be modified but its children might. # Also, we won't copy over any of its attributes. new_node = doc.createElement(child.tagName) cleanup_tree(doc, child, new_node) dest.appendChild(new_node) elif child.getAttribute('data-embed') != '': # This is a video. We want to copy the data-embed value, which is HTML for an iframe node. # So, we have to parse it into a separate document and import the node. iframe_html = child.getAttribute('data-embed') parser = HTMLParser(tree=treebuilders.getTreeBuilder('dom')) iframe_doc = parser.parse(iframe_html) try: iframe = iframe_doc.documentElement.childNodes[1].firstChild if iframe.tagName != 'iframe': raise ValueError() new_node = doc.importNode(iframe, False) # Quora uses a protocol-relative URL (//youtube.com/...) so let's make sure we rewrite this. src = new_node.getAttribute('src') if src.startswith('//'): new_node.setAttribute('src', 'http:' + src) # The video will look really bad if we don't explicitly set the dimensions. new_node.setAttribute('width', '525') new_node.setAttribute('height', '295') dest.appendChild(new_node) except Exception: print('[WARNING] Failed to parse video embed code', file=sys.stderr) # Bail out by just copying the original HTML dest.appendChild(child.cloneNode(True)) elif child.tagName == 'code': # Inline code block. Strip the attributes. new_node = doc.createElement('code') dest.appendChild(new_node) cleanup_tree(doc, child, new_node) elif 'ContentFooter' in child.getAttribute('class') or 'hidden' in child.getAttribute('class'): # These are nodes we just want to skip. continue elif child.tagName in ['span', 'div']: # don't insert a span or div; just insert its contents cleanup_tree(doc, child, dest) elif child.tagName == 'a': # A link. We only want to copy the href, and pass the rest through. new_node = doc.createElement('a') href = child.getAttribute('href') if href.startswith('/'): href = 'http://quora.com' + href new_node.setAttribute('href', href) dest.appendChild(new_node) cleanup_tree(doc, child, new_node) elif child.tagName == 'img': src = child.getAttribute('master_src') if src == '': src = child.getAttribute('src') new_node = doc.createElement('img') new_node.setAttribute('src', src) new_node.setAttribute('alt', child.getAttribute('alt')) if args.no_download: dest.appendChild(new_node) continue # Save a copy of the image locally. # If an error occurs, just leave the src pointing to Quora. try: m = re.search('/([^/?]+)(\?|$)', src) if m is None: raise ValueError() filename = m.group(1) if not filename.endswith('.png'): filename += '.png' try: img_fd = os.open(args.output_dir + '/' + filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL) except OSError as error: if error.errno == errno.EEXIST: log_if_v('Image %s has already been saved; skipping' % filename) new_node.setAttribute('src', filename) continue else: raise log_if_v('Downloading image from %s' % src) closed = False try: img = urllib.request.urlopen(src).read() time.sleep(args.delay) os.write(img_fd, img) os.close(img_fd) closed = True except Exception: os.close(img_fd) closed = True try: os.remove(args.output_dir + '/' + filename) except: print('[WARNING] Failed to remove incomplete file %s' % filename, file=sys.stderr) raise finally: if not closed: os.close(img_fd) # Don't leave the file there; we will retry it next time. # If everything went according to plan, rewrite the src to the local file. new_node.setAttribute('src', filename) except urllib.error.URLError as error: print('[WARNING] Failed to download image from URL %s (%s)' % (src, error.reason), file=sys.stderr) except OSError as error: print('[WARNING] Failed to save image from URL %s to file %s (%s)' % (src, filename, error.strerror), file=sys.stderr) except ValueError: print('[WARNING] Failed to determine image name from URL %s' % src, file=sys.stderr) finally: dest.appendChild(new_node) elif child.tagName == 'pre': # Block (not inline) code. Quora's HTML already has the desired
 structure,
            # so we just need to strip the attributes from the 
.
            new_node = doc.createElement('pre')
            dest.appendChild(new_node)
            cleanup_tree(doc, child, new_node)
        else:
            print('[WARNING] Unrecognized node', file=sys.stderr)
            # Bail out by just copying the original HTML
            dest.appendChild(child.cloneNode(True))

parser = argparse.ArgumentParser(description = 'Convert answers downloaded from Quora into a more portable HTML format')
parser.add_argument('input_dir', nargs='?', default='./quora-answers', help='directory containing "raw" answers downloaded from Quora')
parser.add_argument('output_dir', nargs='?', default='./quora-answers-cooked', help='where to store the images and converted answers')
parser.add_argument('-d', '--delay', default=0, type=float, help='Time to sleep between downloads, in seconds')
parser.add_argument('-n', '--no_download', action='store_true', help='Do not save images')
parser.add_argument('-v', '--verbose', action='store_true', help='be verbose')

global args
args = parser.parse_args()

# Get a list of answers to convert...
filenames = list(filter(lambda f: f.endswith('.html'), os.listdir(args.input_dir)))
filenames.sort()
if len(filenames) == 0:
    sys.exit('[FATAL] No .html files found in directory %s', args.input_dir)
print('Found %d answers' % len(filenames), file=sys.stderr)

log_if_v('Creating directory %s' % args.output_dir)
try:
    os.mkdir(args.output_dir, 0o700)
except OSError as error:
    if error.errno == errno.EEXIST:
        log_if_v('Directory already exists')
    else:
        # This is the top level, and we have nothing else to do if we failed
        raise

for filename in filenames:
    sys.stderr.flush()
    print('Filename: ' + filename, file=sys.stderr)
    try:
        with open(args.input_dir + '/' + filename, 'rb') as page:
            page_html = page.read()
    except IOError as error:
        print('[ERROR] Failed to read %s (%s)' % (filename, error.strerror))
        continue

    # Get the HTML element containing just the answer itself.
    # Also get the title.
    parser = HTMLParser(tree=treebuilders.getTreeBuilder('dom'))
    document = parser.parse(page_html, default_encoding='utf-8')
    title_node = get_title_node(document) 
    log_if_v('Title: ' + ('(could not be determined)' if title_node is None else get_text_content(title_node)))

    answer_node = None
    for node in document.getElementsByTagName('div'):
        if 'ExpandedAnswer' in node.getAttribute('class').split():
            answer_node = node
            break
    if answer_node is None:
        print('[WARNING] Failed to locate answer on page (filename: %s)' % filename, file=sys.stderr)
        continue

    # Construct our new page...
    new_page = document.createElement('html')
    head_node = document.createElement('head')
    if not title_node is None:
        head_node.appendChild(title_node)
    meta_node = document.createElement('meta')
    meta_node.setAttribute('charset', 'utf-8')
    head_node.appendChild(meta_node)
    css = ("blockquote { border-left: 2px solid #ddd; color: #666; margin: 0; padding-left: 16px; } "
           "code, pre { background: #f4f4f4; } "
           "pre, h2 { margin: 0; } "
           "ul { margin: 0 0 0 16px; padding: 8px 0; } "
           "ol { margin: 0 0 0 28px; padding: 8px 0; } "
           "li { margin: 0 0 8px; } ")
    style_node = document.createElement('style')
    style_node.setAttribute('type', 'text/css')
    style_node.appendChild(document.createTextNode(css))
    head_node.appendChild(style_node)
    # Quora now uses MathJax, so set up the configuration object:
    script_node = document.createElement('script')
    script_text = document.createTextNode('window.MathJax = {"showMathMenu":false,"messageStyle":"none","errorSettings":{"style":{"color":"#000000","font-style":"normal"}},"HTML-CSS":{"linebreaks":{"automatic":true,"width":"container"},"EqnChunk":150,"EqnChunkDelay":20},"tex2jax":{"inlineMath":[["[math]","[/math]"]],"displayMath":[],"ignoreClass":"edit_latex|qtext_editor_content|ignore_latex","processClass":"render_latex","processEnvironments":false,"preview":"none"},"TeX":{"noUndefined":{"attributes":{"mathcolor":"red"}},"noErrors":{"multiLine":true,"style":{"max-width":"100%","overflow":"hidden"}},"Macros":{"C":"{\\mathbb{C}}","N":"{\\mathbb{N}}","O":"{\\emptyset}","Q":"{\\mathbb{Q}}","R":"{\\mathbb{R}}","Z":"{\\mathbb{Z}}"}},"fast-preview":{"disabled":true},"Safe":{"allow":{"URLs":"none","classes":"none","cssIDs":"none","styles":"none","fontsize":"none","require":"none"}}};')
    script_node.appendChild(script_text)
    head_node.appendChild(script_node)
    # and then load MathJax:
    script_node = document.createElement('script')
    script_node.setAttribute('type', 'text/javascript')
    script_node.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML,Safe')
    head_node.appendChild(script_node)
    new_page.appendChild(head_node)
    body_node = document.createElement('body')
    # This step processes Quora's HTML into a more lightweight and portable form.
    cleanup_tree(document, answer_node, body_node)
    new_page.appendChild(body_node)
    # Okay! Finally, save the HTML.
    walker = treewalkers.getTreeWalker('dom')(new_page)
    try:
        with open(args.output_dir + '/' + filename, 'wb', 0o600) as saved_page:
            saved_page.write(b'')
            saved_page.write(serializer.serialize(new_page, 'dom', 'utf-8', omit_optional_tags=False))
    except IOError as error:
        print('[ERROR] Failed to save to file %s (%s)' % (filename, error.strerror), file=sys.stderr)

print('Done', file=sys.stderr)



================================================
FILE: crawler.py
================================================
#!/usr/bin/env python3
import argparse
import errno
import json
import os
import re
import sys
import time
import urllib.error
import urllib.request

def log_if_v(msg):
    if args.verbose:
        print('[DEBUG] %s' % msg, file=sys.stderr)

# Given origin (timestamp offset by time zone) and string from Quora, e.g.
# "Added 31 Jan", returns a string such as '2015-01-31'.
# Quora's short date strings don't provide enough information to determine the
# exact time, unless it was within the last day, so we won't bother to be any
# more precise.
def parse_quora_date(origin, quora_str):
    days_of_week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    months_of_year = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    _, _, date_str = quora_str.partition('Added ')
    date_str = date_str.strip()
    if date_str == '':
        raise ValueError('"%s" does not appear to indicate when answer was added' % quora_str)
    m0 = re.match('just now$', date_str)
    m1 = re.match('(\d+)m ago$', date_str)
    m2 = re.match('(\d+)h ago$', date_str)
    m3 = re.match('(' + '|'.join(days_of_week) + ')$', date_str)
    m4 = re.match('(' + '|'.join(months_of_year) + ') (\d+)$', date_str)
    m5 = re.match('(' + '|'.join(months_of_year) + ') (\d+), (\d+)$', date_str)
    m6 = re.match('(\d+)[ap]m$', date_str)
    if not m0 is None or not m6 is None:
        # Using origin for time in am / pm since the time of the day will be discarded anyway
        tm = time.gmtime(origin)
    elif not m1 is None:
        tm = time.gmtime(origin - 60*int(m1.group(1)))
    elif not m2 is None:
        tm = time.gmtime(origin - 3600*int(m2.group(1)))
    elif not m3 is None:
        # Walk backward until we reach the given day of the week
        day_of_week = days_of_week.index(m3.group(1))
        offset = 1
        while offset <= 7:
            tm = time.gmtime(origin - 86400*offset)
            if tm.tm_wday == day_of_week:
                break
            offset += 1
        else:
            raise ValueError('date "%s" is invalid' % date_str)
    elif not m4 is None:
        # Walk backward until we reach the given month and year
        month_of_year = months_of_year.index(m4.group(1)) + 1
        day_of_month = int(m4.group(2))
        offset = 1
        while offset <= 366:
            tm = time.gmtime(origin - 86400*offset)
            if tm.tm_mon == month_of_year and tm.tm_mday == day_of_month:
                break
            offset += 1
        else:
            raise ValueError('date "%s" is invalid' % date_str)
    elif not m5 is None:
        # may raise ValueError
        tm = time.strptime(date_str, '%b %d, %Y')
    else:
        raise ValueError('date "%s" could not be interpreted' % date_str)
    return '%d-%02d-%02d' % (tm.tm_year, tm.tm_mon, tm.tm_mday)

parser = argparse.ArgumentParser(description = 'Download a set of answers from Quora')
parser.add_argument('input_file', help='file containing JSON-encoded list of timestamped URLs to download')
parser.add_argument('output_dir', nargs='?', default='./quora-answers', help='where to store the downloaded answers and images')
parser.add_argument('-d', '--delay', default=0, type=float, help='Time to sleep between answers, in seconds')
parser.add_argument('-t', '--origin_timestamp', default=None, type=int, help='JS time when the list of URLs was fetched')
parser.add_argument('-z', '--origin_timezone', default=None, type=int, help='browser timezone')
parser.add_argument('-v', '--verbose', action='store_true', help='enable debug messages')
parser.add_argument('-o', '--overwrite', action='store_true', help='Overwrite existing answers')

global args
args = parser.parse_args()

# Determine the origin for relative date computation
if args.origin_timestamp is None:
    log_if_v('Using current time')
    args.origin_timestamp = time.time()
else:
    args.origin_timestamp //= 1000
if args.origin_timezone is None:
    log_if_v('Using system time zone')
    args.origin_timezone = time.timezone
else:
    args.origin_timezone *= 60
origin = args.origin_timestamp - args.origin_timezone

# Load the list of answer URLs from the input file.
log_if_v('Loading input file %s' % args.input_file)
with open(args.input_file, 'rb') as input_file:
    answers = json.load(input_file)
print('Found %d answers' % len(answers), file=sys.stderr)

# Check the validity of the input
if type(answers) != list:
    sys.exit('[FATAL] Incorrect input format')
for e in answers:
    if type(e) != list or len(e) != 2 or type(e[0]) != str or type(e[1]) != str:
        sys.exit('[FATAL] Incorrect input format')

log_if_v('Creating directory %s' % args.output_dir)
try:
    os.mkdir(args.output_dir, 0o700)
except OSError as error:
    if error.errno == errno.EEXIST:
        log_if_v('Directory already exists')
    else:
        # This is the top level, and we have nothing else to do if we failed
        raise
os.chdir(args.output_dir)
download_file_count = 0
for e in answers:
    sys.stderr.flush()
    url = e[0]
    print('URL: %s' % url, file=sys.stderr)

    # Determine the date when this answer was written
    try:
        added_time = parse_quora_date(origin, e[1])
    except ValueError as error:
        print('[WARNING] Failed to parse date: %s' % str(error), file=sys.stderr)
        added_time = 'xxxx-xx-xx'
    print('Date: %s' % added_time, file=sys.stderr)

    # Get the part of the URL indicating the question title; we will save under this name
    m1 = re.search('quora\.com/([^/]+)/answer', url)
    # if there's a context topic
    m2 = re.search('quora\.com/[^/]+/([^/]+)/answer', url)
    filename = added_time + ' '
    if not m1 is None:
        filename += m1.group(1)
    elif not m2 is None:
        filename += m2.group(1)
    else:
        print('[ERROR] Could not find question part of URL %s; skipping' % url, file=sys.stderr)
        continue
    # Trim the filename if it's too long. 255 bytes is the limit on many filesystems.
    total_byte_length = len(bytes(filename + '.html', encoding="utf-8"))
    filename_bytes = bytes(filename, encoding="utf-8")
    if total_byte_length > 255:
        filename_bytes = filename_bytes[:255-total_byte_length]
        well_formed = False
        while not well_formed:
            try:
                filename = str(filename_bytes, encoding="utf-8")
                well_formed = True
            except UnicodeDecodeError:
                filename_bytes = filename_bytes[:-1]
        log_if_v('Filename was truncated to at most 255 bytes.')
    filename += '.html'
    log_if_v('Filename: %s' % filename)

    # If overwrite is enabled or the answer doesn't exist
    if args.overwrite or not os.path.isfile(filename):
        # Fetch the URL to find the answer
        log_if_v('Downloading answer from URL %s' % url)
        try:
            page_html = urllib.request.urlopen(url).read()
            with open(filename, 'wb') as f:
                f.write(page_html)
        except urllib.error.URLError as error:
            print('[ERROR] Failed to download answer from URL %s (%s)' % (url, error.reason), file=sys.stderr)
            continue
        except IOError as error:
            print('[ERROR] Failed to save answer to file %s (%s)' % (filename, error.strerror), file=sys.stderr)

        download_file_count += 1
        time.sleep(args.delay)
    else:
        log_if_v('Answer File : %s Already Exists. Skipping' % filename)

print('Done. Downloaded %d files' % download_file_count, file=sys.stderr)