Last active
May 4, 2017 09:20
-
-
Save orsinium/d6a491eb9da7c1b8e333fb6223ae8982 to your computer and use it in GitHub Desktop.
Search on stackoverflow from console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from grab import Grab | |
g = Grab() | |
def myprint(text): | |
while len(text) > 80: | |
substr = text[:80] | |
endofline = max(substr.rfind('\n'), substr.rfind(' ')) | |
if not endofline: | |
endofline = 80 | |
print(text[:endofline]) | |
text = text[endofline+1:] | |
print(text) | |
from sys import argv | |
from urllib.parse import quote | |
from re import compile | |
rex_colorize = compile('<a.*>') | |
rex_clearize = compile('<.*>') | |
transforms = ( | |
('code', '\x1B[32m'), | |
('b', '\x1B[31m'), | |
('p', '\n'), | |
('pre', '\n'), | |
) | |
query = 'http://www.google.ru/search?q={}%20site:stackoverflow.com' | |
query = query.format(quote(' '.join(argv[1:]))) | |
#print(query) | |
g.go(query) | |
for link in g.doc.select('//h3[@class="r"]//a'): | |
print('\x1B[33m'+link.text()+'\x1B[0m') | |
link = link.attr('href') | |
print('\x1B[33m'+link+'\x1B[0m') | |
g.go(link) | |
for answer in g.doc.select('//*[@class="answer"]//*[@class="post-text"]'): | |
answer = answer.html() | |
#answer = answer.replace('\n', ' ') | |
for before, after in transforms: | |
answer = answer.replace('<'+before+'>', after) | |
answer = answer.replace('</'+before+'>', '\x1B[0m') | |
answer = rex_colorize.sub('\x1B[33m', answer) | |
answer = answer.replace('</a>', '\x1B[0m') | |
answer = rex_clearize.sub('', answer) | |
#while ' ' in answer: | |
# answer = answer.replace(' ', ' ') | |
while '\n\n' in answer: | |
answer = answer.replace('\n\n', '\n') | |
answer = answer.strip() | |
print('-'*80) | |
myprint(answer) | |
try: | |
if input('> ') in ('next', ' '): | |
break | |
except (EOFError, KeyboardInterrupt): | |
print('\nExit.') | |
exit() | |
print("Sorry. It's all...") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment