Jak pobrać losowy cytat z Basha

Coldpeer

Można do tego celu wykorzystać moduł urllib2:

import urllib2
from re import findall, DOTALL

def bash():
    u = urllib2.urlopen('http://bash.org.pl/random')
    q = findall('<p class="quote">(.*?)</p>', u.read().decode('utf-8'), DOTALL)
    return q[0].replace('&lt;', '<').replace('&gt;', '>').replace('<br />', '\n')

print bash()

Czy np. moduł <url=http://docs.python.org/lib/module-httplib.html>httplib<url>:

from httplib import HTTPConnection
from re import findall, DOTALL

def bash():
    u = HTTPConnection('bash.org.pl')
    u.request('GET', '/random')
    r = u.getresponse()
    if str(r.status) == '200':
	q = findall('<p class="quote">(.*?)</p>', r.read().decode('utf-8'), DOTALL)
        q = q[0].replace('&lt;', '<').replace('&gt;', '>').replace('<br />', '\n')
    u.close()
    return q

print bash()

2 komentarzy