на диете

10:04 | 20-12-2013 | HOWTO, Software | 3 Comments

у каждого из нас, полагаю, есть такой новостной сайт (рассадник каких-нибудь деревенских акуталий), что совсем уж невозможно просматривать из-за окончательного засилия рекламы, аляповатого дизайна и прочих разных глупостей. что ж, дабы не рыться среди чужой безвкусицы, можно просто взять с главной страницы заголовки — и в python это легко сделать с помощью библиотеки BeautifulSoup:

#!/usr/bin/env python

import sys
import urllib2
from BeautifulSoup import BeautifulSoup
# in order to use Beautiful Soup library version 4 
# comment the above line and uncomment the one below
# from bz4 import BeautifulSoup

# get data from your beloved ugly website
data = urllib2.urlopen('http://your.ugly.website')
# parse that data
soup = BeautifulSoup(data.read())
# describe the type of the output
print 'Content-type: text/html\n\n'
# extract headers of interest
for header in soup.html.body.findAll('tags and styles go here'):
# detect if the links in question are relative or absolute
        if '"/' in str(header):
# correct relative ones
                print(re.sub('"/','"http://your.ugly.website',str(header)))
        else:
                print(str(header))

а для того, чтобы запустить этот скрипт на сервере, сохраните отредатированный код в файл с расширением .cgi и добавьте в файл .htaccess данного каталога следующие директивы:

Options +ExecCGI
AddHandler cgi-script .cgi

ниже, в комментариях, так же есть и законченный пример.

  

3 Responses to “на диете”

  1. s says:

    вот, например, так:

    #!/usr/bin/env python
    
    import re
    import sys
    import urllib2
    from BeautifulSoup import BeautifulSoup
    # In order to use Beautiful Soup library version 4 
    # comment the above line and uncomment the one below
    # from bz4 import BeautifulSoup
    
    # no offence to lenta.ru, it's just an example
    data = urllib2.urlopen('http://lenta.ru')
    # parse that data
    soup = BeautifulSoup(data.read())
    soup = BeautifulSoup(data.read())
    # describe the type of the output
    print 'Content-type: text/html\n\n'
    # add some style definitions
    print '<style type="text/css">'
    print 'body {'
    print 'font-family:verdana,sans-serif;'
    print 'font-size: 13px;'
    print 'line-height: 25px;'
    print '</style>'
    # extract headers of interest
    for header in soup.html.body.findAll('div', attrs={'class': 'first-item'}):
    # strip all the garbage ('.*?' is a non-greedy match)
            header = re.sub('<a.*><img.*?/>.</a>','',str(header), 0, re.DOTALL)
            header = re.sub('<div class="more">.*?</div>', '', str(header), 0, re.DOTALL)
            header = re.sub('<time.*?</time>','',str(header))
            header = re.sub('</?h2>','',str(header))
    # detect if the links in question are relative or absolute
            if '"/' in str(header):
    # correct relative ones
                    print(re.sub('"/','"http://lenta.ru/',str(header)))
            else:
                    print(str(header))
    # extract another portion of headers
    for header in soup.html.body.findAll('div', attrs={'class': 'item'}):
            header = re.sub('<time.*</time>','',str(header))
            header = re.sub('<span.*</span>','',str(header))
            header = re.sub('</?h3>','',str(header))
    # detect if the links in question are relative or absolute
            if '"/' in str(header):
    # correct relative ones
                    sys.stdout.write(re.sub('"/','"http://lenta.ru/',str(header)))
            else:
                    print(str(header))
    


  2. […] или вот Newspaper, другая python-библиотека, что находит и обрабатывает заголовки и статьи в интернете, с легкостью превращая новостные сайты в забытые газеты. […]

Leave a Reply