# beautifulsoup.py - parser functions for html content
#
# Copyright (C) 2007, 2008, 2009 Arthur de Jong
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# The files produced as output from the software do not automatically fall
# under the copyright of the software, unless explicitly stated otherwise.
"""Parser functions for processing HTML content. This module uses the
BeautifulSoup HTML parser and is more flexible than the legacy HTMLParser
module."""
import urlparse
import crawler
import re
import htmlentitydefs
import BeautifulSoup
import myurllib
from parsers.html import htmlunescape
# pattern for matching http-equiv and content part of
#
_refreshhttpequivpattern = re.compile('^refresh$', re.I)
_refershcontentpattern = re.compile('^[0-9]+;url=(.*)$', re.I)
# check BeautifulSoup find() function for bugs
if BeautifulSoup.BeautifulSoup('').find('foo', bar=True):
import debugio
debugio.warn('using buggy version of BeautifulSoup (%s)' % BeautifulSoup.__version__)
def parse(content, link):
"""Parse the specified content and extract an url list, a list of images a
title and an author. The content is assumed to contain HMTL."""
# create parser and feed it the content
soup = BeautifulSoup.BeautifulSoup(content,
fromEncoding=str(link.encoding))
# fetch document encoding
link.set_encoding(soup.originalEncoding)
# TITLE
title = soup.find('title')
if title and title.string:
link.title = htmlunescape(title.string).strip()
# FIXME: using myurllib.normalizeurl is wrong below, we should probably use
# something like link.urlunescape() to do the escaping and check
# and log at the same time
#
base = soup.find('base', href=True)
if base:
base = myurllib.normalizeurl(htmlunescape(base['href']).strip())
else:
base = link.url
#
for l in soup.findAll('link', rel=True, href=True):
if l['rel'].lower() in ('stylesheet', 'alternate stylesheet', 'icon', 'shortcut icon'):
embed = myurllib.normalizeurl(htmlunescape(l['href']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
#
author = soup.find('meta', attrs={'name': re.compile("^author$", re.I), 'content': True})
if author and author['content']:
link.author = htmlunescape(author['content']).strip()
#
refresh = soup.find('meta', attrs={'http-equiv': _refreshhttpequivpattern, 'content': True})
if refresh and refresh['content']:
try:
child = _refershcontentpattern.search(refresh['content']).group(1)
link.add_child(urlparse.urljoin(base, child))
except AttributeError:
# ignore cases where refresh header parsing causes problems
pass
#
for img in soup.findAll('img', src=True):
embed = myurllib.normalizeurl(htmlunescape(img['src']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
#
for a in soup.findAll('a', href=True):
child = myurllib.normalizeurl(htmlunescape(a['href']).strip())
if child:
link.add_child(urlparse.urljoin(base, child))
#
# TODO: consistent url escaping?
for a in soup.findAll('a', attrs={'name': True}):
# get anchor name
a_name = myurllib.normalizeurl(htmlunescape(a['name']).strip())
# if both id and name are used they should be the same
if a.has_key('id') and a_name != myurllib.normalizeurl(htmlunescape(a['id']).strip()):
link.add_pageproblem(
'anchors defined in name and id attributes do not match')
# add the id anchor anyway
link.add_anchor(myurllib.normalizeurl(htmlunescape(a['id']).strip()))
# add the anchor
link.add_anchor(a_name)
#
for elem in soup.findAll(id=True):
# skip anchor that have a name
if elem.name == 'a' and elem.has_key('name'):
continue
# add the anchor
link.add_anchor(myurllib.normalizeurl(htmlunescape(elem['id']).strip()))
#
for frame in soup.findAll('frame', src=True):
embed = myurllib.normalizeurl(htmlunescape(frame['src']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
#