Path: blob/master/venv/Lib/site-packages/bs4/diagnose.py
811 views
"""Diagnostic functions, mainly for use when doing tech support."""12# Use of this source code is governed by the MIT license.3__license__ = "MIT"45import cProfile6from io import StringIO7from html.parser import HTMLParser8import bs49from bs4 import BeautifulSoup, __version__10from bs4.builder import builder_registry1112import os13import pstats14import random15import tempfile16import time17import traceback18import sys19import cProfile2021def diagnose(data):22"""Diagnostic suite for isolating common problems.2324:param data: A string containing markup that needs to be explained.25:return: None; diagnostics are printed to standard output.26"""27print(("Diagnostic running on Beautiful Soup %s" % __version__))28print(("Python version %s" % sys.version))2930basic_parsers = ["html.parser", "html5lib", "lxml"]31for name in basic_parsers:32for builder in builder_registry.builders:33if name in builder.features:34break35else:36basic_parsers.remove(name)37print((38"I noticed that %s is not installed. Installing it may help." %39name))4041if 'lxml' in basic_parsers:42basic_parsers.append("lxml-xml")43try:44from lxml import etree45print(("Found lxml version %s" % ".".join(map(str,etree.LXML_VERSION))))46except ImportError as e:47print(48"lxml is not installed or couldn't be imported.")495051if 'html5lib' in basic_parsers:52try:53import html5lib54print(("Found html5lib version %s" % html5lib.__version__))55except ImportError as e:56print(57"html5lib is not installed or couldn't be imported.")5859if hasattr(data, 'read'):60data = data.read()61elif data.startswith("http:") or data.startswith("https:"):62print(('"%s" looks like a URL. Beautiful Soup is not an HTTP client.' % data))63print("You need to use some other library to get the document behind the URL, and feed that document to Beautiful Soup.")64return65else:66try:67if os.path.exists(data):68print(('"%s" looks like a filename. Reading data from the file.' % data))69with open(data) as fp:70data = fp.read()71except ValueError:72# This can happen on some platforms when the 'filename' is73# too long. Assume it's data and not a filename.74pass75print("")7677for parser in basic_parsers:78print(("Trying to parse your markup with %s" % parser))79success = False80try:81soup = BeautifulSoup(data, features=parser)82success = True83except Exception as e:84print(("%s could not parse the markup." % parser))85traceback.print_exc()86if success:87print(("Here's what %s did with the markup:" % parser))88print((soup.prettify()))8990print(("-" * 80))9192def lxml_trace(data, html=True, **kwargs):93"""Print out the lxml events that occur during parsing.9495This lets you see how lxml parses a document when no Beautiful96Soup code is running. You can use this to determine whether97an lxml-specific problem is in Beautiful Soup's lxml tree builders98or in lxml itself.99100:param data: Some markup.101:param html: If True, markup will be parsed with lxml's HTML parser.102if False, lxml's XML parser will be used.103"""104from lxml import etree105for event, element in etree.iterparse(StringIO(data), html=html, **kwargs):106print(("%s, %4s, %s" % (event, element.tag, element.text)))107108class AnnouncingParser(HTMLParser):109"""Subclass of HTMLParser that announces parse events, without doing110anything else.111112You can use this to get a picture of how html.parser sees a given113document. The easiest way to do this is to call `htmlparser_trace`.114"""115116def _p(self, s):117print(s)118119def handle_starttag(self, name, attrs):120self._p("%s START" % name)121122def handle_endtag(self, name):123self._p("%s END" % name)124125def handle_data(self, data):126self._p("%s DATA" % data)127128def handle_charref(self, name):129self._p("%s CHARREF" % name)130131def handle_entityref(self, name):132self._p("%s ENTITYREF" % name)133134def handle_comment(self, data):135self._p("%s COMMENT" % data)136137def handle_decl(self, data):138self._p("%s DECL" % data)139140def unknown_decl(self, data):141self._p("%s UNKNOWN-DECL" % data)142143def handle_pi(self, data):144self._p("%s PI" % data)145146def htmlparser_trace(data):147"""Print out the HTMLParser events that occur during parsing.148149This lets you see how HTMLParser parses a document when no150Beautiful Soup code is running.151152:param data: Some markup.153"""154parser = AnnouncingParser()155parser.feed(data)156157_vowels = "aeiou"158_consonants = "bcdfghjklmnpqrstvwxyz"159160def rword(length=5):161"Generate a random word-like string."162s = ''163for i in range(length):164if i % 2 == 0:165t = _consonants166else:167t = _vowels168s += random.choice(t)169return s170171def rsentence(length=4):172"Generate a random sentence-like string."173return " ".join(rword(random.randint(4,9)) for i in list(range(length)))174175def rdoc(num_elements=1000):176"""Randomly generate an invalid HTML document."""177tag_names = ['p', 'div', 'span', 'i', 'b', 'script', 'table']178elements = []179for i in range(num_elements):180choice = random.randint(0,3)181if choice == 0:182# New tag.183tag_name = random.choice(tag_names)184elements.append("<%s>" % tag_name)185elif choice == 1:186elements.append(rsentence(random.randint(1,4)))187elif choice == 2:188# Close a tag.189tag_name = random.choice(tag_names)190elements.append("</%s>" % tag_name)191return "<html>" + "\n".join(elements) + "</html>"192193def benchmark_parsers(num_elements=100000):194"""Very basic head-to-head performance benchmark."""195print(("Comparative parser benchmark on Beautiful Soup %s" % __version__))196data = rdoc(num_elements)197print(("Generated a large invalid HTML document (%d bytes)." % len(data)))198199for parser in ["lxml", ["lxml", "html"], "html5lib", "html.parser"]:200success = False201try:202a = time.time()203soup = BeautifulSoup(data, parser)204b = time.time()205success = True206except Exception as e:207print(("%s could not parse the markup." % parser))208traceback.print_exc()209if success:210print(("BS4+%s parsed the markup in %.2fs." % (parser, b-a)))211212from lxml import etree213a = time.time()214etree.HTML(data)215b = time.time()216print(("Raw lxml parsed the markup in %.2fs." % (b-a)))217218import html5lib219parser = html5lib.HTMLParser()220a = time.time()221parser.parse(data)222b = time.time()223print(("Raw html5lib parsed the markup in %.2fs." % (b-a)))224225def profile(num_elements=100000, parser="lxml"):226"""Use Python's profiler on a randomly generated document."""227filehandle = tempfile.NamedTemporaryFile()228filename = filehandle.name229230data = rdoc(num_elements)231vars = dict(bs4=bs4, data=data, parser=parser)232cProfile.runctx('bs4.BeautifulSoup(data, parser)' , vars, vars, filename)233234stats = pstats.Stats(filename)235# stats.strip_dirs()236stats.sort_stats("cumulative")237stats.print_stats('_html5lib|bs4', 50)238239# If this file is run as a script, standard input is diagnosed.240if __name__ == '__main__':241diagnose(sys.stdin.read())242243244