Parsing HTML with BeautifulSoup

This is how you parse HTML using BeautifulSoup. I will add more detail when I get five minutes :)

import urllib2

from bs4 import BeautifulSoup

import re


def parse_url(my_url, find_criteria):
    header = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
        'Accept-Encoding': 'none',
        'Accept-Language': 'en-US,en;q=0.8',
        'Connection': 'keep-alive'}

    request = urllib2.Request(my_url, headers=header)

    my_content = urllib2.urlopen(request)

    my_soup = BeautifulSoup(my_content)

    my_titles = my_soup.find_all("a", href=re.compile(find_criteria))

    for each in my_titles:
        names = each.contents[0]
        full_link = each.get('href')
        print (names)
        print (full_link)
    print "-" * 40


def main():
    parse_url("http://ssvc.org.uk/phpbb/viewforum.php?f=4", "viewtopic\.php.*")
    parse_url("http://volkszone.com/VZi/forumdisplay.php?f=46", "showthread\.php.*")
    parse_url("http://www.thesamba.com/vw/classifieds/cat.php?id=31", "detail\.php.*")


if __name__ == '__main__':
    main()

Author | Miles Davenport

Career programmer, who designs, assembles, fixes, and supports customers, software and systems.