1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
|
# 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 bs4
import myurllib
from parsers.html import htmlunescape
# pattern for matching http-equiv and content part of
# <meta http-equiv="refresh" content="0;url=URL">
_refreshhttpequivpattern = re.compile('^refresh$', re.I)
_refershcontentpattern = re.compile('^[0-9]+;url=(.*)$', re.I)
# check BeautifulSoup find() function for bugs
# not needed for bs4
#if BeautifulSoup.BeautifulSoup('<foo>').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 = bs4.BeautifulSoup(content,
from_encoding=str(link.encoding),
features="lxml")
# fetch document encoding
link.set_encoding(soup.originalEncoding)
# <title>TITLE</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 href="URL">
base = soup.find('base', href=True)
if base:
base = myurllib.normalizeurl(htmlunescape(base['href']).strip())
else:
base = link.url
# <link rel="TYPE" href="URL">
for l in soup.find_all('link', rel=True, href=True):
# Note that l['rel'] could be a list, strictly speaking, so take first element
if l['rel'][0].lower() in ('stylesheet', 'alternate stylesheet', 'icon', 'shortcut icon'):
embed = myurllib.normalizeurl(htmlunescape(l['href']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
# <meta name="author" content="AUTHOR">
author = soup.find('meta', attrs={'name': re.compile("^author$", re.I), 'content': True})
if author and author['content']:
link.author = htmlunescape(author['content']).strip()
# <meta http-equiv="refresh" content="0;url=URL">
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
# <img src="URL">
for img in soup.find_all('img', src=True):
embed = myurllib.normalizeurl(htmlunescape(img['src']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
# <a href="URL">
for a in soup.find_all('a', href=True):
child = myurllib.normalizeurl(htmlunescape(a['href']).strip())
if child:
link.add_child(urlparse.urljoin(base, child))
# <a name="NAME">
# TODO: consistent url escaping?
for a in soup.find_all('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_attr('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)
# <ANY id="ID">
for elem in soup.find_all(id=True):
# skip anchor that have a name
if elem.name == 'a' and elem.has_attr('name'):
continue
# add the anchor
link.add_anchor(myurllib.normalizeurl(htmlunescape(elem['id']).strip()))
# <frameset><frame src="URL"...>...</frameset>
for frame in soup.find_all('frame', src=True):
embed = myurllib.normalizeurl(htmlunescape(frame['src']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
# <iframe src="URL"...>
for frame in soup.find_all('iframe', src=True):
embed = myurllib.normalizeurl(htmlunescape(frame['src']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
# <object data="URL"...>
for obj in soup.find_all('object', data=True):
embed = myurllib.normalizeurl(htmlunescape(obj['data']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
# <object><param name="movie" value="URL"...></object>
for para in soup.find_all('param', attrs={'name': 'movie', 'value': True}):
embed = myurllib.normalizeurl(htmlunescape(para['value']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
# <map><area href="URL"...>...</map>
for area in soup.find_all('area', href=True):
child = myurllib.normalizeurl(htmlunescape(area['href']).strip())
if child:
link.add_child(urlparse.urljoin(base, child))
# <applet code="URL" [archive="URL"]...>
for applet in soup.find_all('applet', code=True):
# if applet has archive tag check that
if applet.has_attr('archive'):
embed = myurllib.normalizeurl(htmlunescape(applet['archive']).strip())
else:
embed = myurllib.normalizeurl(htmlunescape(applet['code']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
# <embed src="URL"...>
for embedd in soup.find_all('frame', src=True):
embed = myurllib.normalizeurl(htmlunescape(embedd['src']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
# <embed><param name="movie" value="url"></embed>
for param in soup.find_all('param', attrs={'name': re.compile("^movie$", re.I), 'value': True}):
embed = myurllib.normalizeurl(htmlunescape(param['value']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
# <style>content</style>
for style in soup.find_all('style'):
if style.string:
# delegate handling of inline css to css module
import parsers.css
parsers.css.parse(htmlunescape(style.string), link, base)
# <ANY style="CSS">
for elem in soup.find_all(style=True):
# delegate handling of inline css to css module
import parsers.css
parsers.css.parse(elem['style'], link, base)
# <script src="url">
for script in soup.find_all('script', src=True):
embed = myurllib.normalizeurl(htmlunescape(script['src']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
# <body|table|td background="url">
for t in soup.find_all( ('body', 'table', 'td'), background=True):
embed = myurllib.normalizeurl(htmlunescape(t['background']).strip())
if embed:
link.add_embed(urlparse.urljoin(base, embed))
# flag that the link contains a valid page
link.ispage = True
|