Skip to content

Instantly share code, notes, and snippets.

@ddksr
Created February 1, 2015 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddksr/ae9d9302665e555954fd to your computer and use it in GitHub Desktop.
Save ddksr/ae9d9302665e555954fd to your computer and use it in GitHub Desktop.
Termania script
#!/usr/bin/env python3
"""Termania api
Usage:
termania [options] [QUERY [QUERY ...]]
Options:
-h --help Show this screen.
--version Show version.
"""
from urllib.request import urlopen
from urllib.parse import urlencode
import re
from pyquery import PyQuery as pq
from docopt import docopt
SEARCH_URL = 'http://www.termania.net/iskanje?{}'
LINE_QUERY = '{}: '
LINE_NAME=' * [{}] {}'
LINE_OPT='\n {} '
NL = '\n'
def search(query):
print(LINE_QUERY.format(query))
result = pq(url=SEARCH_URL.format(urlencode({ 'Query': query })),
opener=lambda url, **kw: urlopen(url).read())
for li in result("#results .center .left.listing li"):
lang = li.find('img').attrib.get('title')
name = li.find('h4')
print(LINE_NAME.format(lang, name.text_content()), end='')
has_images = False
for elt in li.find('p'):
if elt.tag == 'img':
has_images = True
break
i = 1
p_content = li.find('p').text_content()
no_strong = True
for p in li.find('p'):
if p.tag == 'img':
lang = p.attrib.get('title')
if not lang: continue
print (LINE_OPT.format(lang), end='')
elif p.tag == 'strong':
content = p.text_content()
if not content: continue
no_strong = False
if not has_images:
print (LINE_OPT.format(str(i) + '.'), end='')
if re.match(r'^\d+\. .+', content):
print (LINE_OPT.format(content), end='')
else:
print (content + ' ', end='')
i += 1
if no_strong:
print (p_content, end='')
print(NL)
if __name__ == '__main__':
arguments = docopt(__doc__, version='0.1')
queries = arguments.get('QUERY')
if queries:
search(' '.join(queries))
else:
import subprocess
p = subprocess.Popen(['xclip', '-o'], stdout=subprocess.PIPE)
out, err = p.communicate()
if not err:
search(out.decode('utf8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment