2013-11-09 17:20:53 +00:00
|
|
|
#!/usr/bin/python3
|
|
|
|
|
|
|
|
|
|
import argparse
|
2013-11-09 18:01:43 +00:00
|
|
|
import http.client
|
2013-11-09 17:20:53 +00:00
|
|
|
import sys
|
|
|
|
|
|
2013-11-09 18:01:43 +00:00
|
|
|
from urllib.parse import urlparse
|
2013-11-09 17:20:53 +00:00
|
|
|
|
|
|
|
|
def get_page(url):
|
|
|
|
|
'''download page and decode it to utf-8'''
|
2013-11-09 18:01:43 +00:00
|
|
|
charset = 'utf-8'
|
|
|
|
|
|
|
|
|
|
up = urlparse(url)
|
|
|
|
|
|
|
|
|
|
headers = {
|
|
|
|
|
"Host": up.netloc,
|
|
|
|
|
"Content-Type": "text/html; charset=utf-8",
|
|
|
|
|
"Connection": "keep-alive",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if up.scheme == 'http':
|
|
|
|
|
conn = http.client.HTTPConnection(up.netloc)
|
|
|
|
|
elif up.scheme == 'https':
|
|
|
|
|
conn = http.client.HTTPSConnection(up.netloc)
|
|
|
|
|
else:
|
|
|
|
|
print("ERROR: invalid protocol set in '{0}'".format(url))
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
conn.request("GET", up.path, None, headers)
|
|
|
|
|
response = conn.getresponse()
|
|
|
|
|
|
|
|
|
|
# determine page charset
|
|
|
|
|
contenttype = response.getheader('Content-Type')
|
|
|
|
|
if contenttype:
|
|
|
|
|
charset = contenttype.split('; ')[1].split('=')[1]
|
|
|
|
|
|
|
|
|
|
page_binary = response.read()
|
|
|
|
|
page = page_binary.decode(charset)
|
|
|
|
|
|
|
|
|
|
return page
|
2013-11-09 17:20:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def write_file(page):
|
|
|
|
|
with open('tmp.html', 'w') as a_file:
|
|
|
|
|
a_file.write(page)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
parser = argparse.ArgumentParser(description=
|
|
|
|
|
'Nevernote - download pages locally.')
|
|
|
|
|
parser.add_argument('urls', metavar='URL', type=str, nargs='+', help=
|
|
|
|
|
'URL of page to download')
|
|
|
|
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
|
|
for url in args.urls:
|
|
|
|
|
page = get_page(url)
|
|
|
|
|
write_file(page)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
sys.exit(main())
|