Path: blob/master/venv/Lib/site-packages/bs4/tests/test_tree.py
811 views
# -*- coding: utf-8 -*-1"""Tests for Beautiful Soup's tree traversal methods.23The tree traversal methods are the main advantage of using Beautiful4Soup over just using a parser.56Different parsers will build different Beautiful Soup trees given the7same markup, but all Beautiful Soup trees can be traversed with the8methods tested here.9"""1011from pdb import set_trace12import copy13import pickle14import re15import warnings16from bs4 import BeautifulSoup17from bs4.builder import (18builder_registry,19HTMLParserTreeBuilder,20)21from bs4.element import (22PY3K,23CData,24Comment,25Declaration,26Doctype,27Formatter,28NavigableString,29Script,30SoupStrainer,31Stylesheet,32Tag,33TemplateString,34)35from bs4.testing import (36SoupTest,37skipIf,38)39from soupsieve import SelectorSyntaxError4041XML_BUILDER_PRESENT = (builder_registry.lookup("xml") is not None)42LXML_PRESENT = (builder_registry.lookup("lxml") is not None)4344class TreeTest(SoupTest):4546def assertSelects(self, tags, should_match):47"""Make sure that the given tags have the correct text.4849This is used in tests that define a bunch of tags, each50containing a single string, and then select certain strings by51some mechanism.52"""53self.assertEqual([tag.string for tag in tags], should_match)5455def assertSelectsIDs(self, tags, should_match):56"""Make sure that the given tags have the correct IDs.5758This is used in tests that define a bunch of tags, each59containing a single string, and then select certain strings by60some mechanism.61"""62self.assertEqual([tag['id'] for tag in tags], should_match)636465class TestFind(TreeTest):66"""Basic tests of the find() method.6768find() just calls find_all() with limit=1, so it's not tested all69that thouroughly here.70"""7172def test_find_tag(self):73soup = self.soup("<a>1</a><b>2</b><a>3</a><b>4</b>")74self.assertEqual(soup.find("b").string, "2")7576def test_unicode_text_find(self):77soup = self.soup('<h1>Räksmörgås</h1>')78self.assertEqual(soup.find(string='Räksmörgås'), 'Räksmörgås')7980def test_unicode_attribute_find(self):81soup = self.soup('<h1 id="Räksmörgås">here it is</h1>')82str(soup)83self.assertEqual("here it is", soup.find(id='Räksmörgås').text)848586def test_find_everything(self):87"""Test an optimization that finds all tags."""88soup = self.soup("<a>foo</a><b>bar</b>")89self.assertEqual(2, len(soup.find_all()))9091def test_find_everything_with_name(self):92"""Test an optimization that finds all tags with a given name."""93soup = self.soup("<a>foo</a><b>bar</b><a>baz</a>")94self.assertEqual(2, len(soup.find_all('a')))9596class TestFindAll(TreeTest):97"""Basic tests of the find_all() method."""9899def test_find_all_text_nodes(self):100"""You can search the tree for text nodes."""101soup = self.soup("<html>Foo<b>bar</b>\xbb</html>")102# Exact match.103self.assertEqual(soup.find_all(string="bar"), ["bar"])104self.assertEqual(soup.find_all(text="bar"), ["bar"])105# Match any of a number of strings.106self.assertEqual(107soup.find_all(text=["Foo", "bar"]), ["Foo", "bar"])108# Match a regular expression.109self.assertEqual(soup.find_all(text=re.compile('.*')),110["Foo", "bar", '\xbb'])111# Match anything.112self.assertEqual(soup.find_all(text=True),113["Foo", "bar", '\xbb'])114115def test_find_all_limit(self):116"""You can limit the number of items returned by find_all."""117soup = self.soup("<a>1</a><a>2</a><a>3</a><a>4</a><a>5</a>")118self.assertSelects(soup.find_all('a', limit=3), ["1", "2", "3"])119self.assertSelects(soup.find_all('a', limit=1), ["1"])120self.assertSelects(121soup.find_all('a', limit=10), ["1", "2", "3", "4", "5"])122123# A limit of 0 means no limit.124self.assertSelects(125soup.find_all('a', limit=0), ["1", "2", "3", "4", "5"])126127def test_calling_a_tag_is_calling_findall(self):128soup = self.soup("<a>1</a><b>2<a id='foo'>3</a></b>")129self.assertSelects(soup('a', limit=1), ["1"])130self.assertSelects(soup.b(id="foo"), ["3"])131132def test_find_all_with_self_referential_data_structure_does_not_cause_infinite_recursion(self):133soup = self.soup("<a></a>")134# Create a self-referential list.135l = []136l.append(l)137138# Without special code in _normalize_search_value, this would cause infinite139# recursion.140self.assertEqual([], soup.find_all(l))141142def test_find_all_resultset(self):143"""All find_all calls return a ResultSet"""144soup = self.soup("<a></a>")145result = soup.find_all("a")146self.assertTrue(hasattr(result, "source"))147148result = soup.find_all(True)149self.assertTrue(hasattr(result, "source"))150151result = soup.find_all(text="foo")152self.assertTrue(hasattr(result, "source"))153154155class TestFindAllBasicNamespaces(TreeTest):156157def test_find_by_namespaced_name(self):158soup = self.soup('<mathml:msqrt>4</mathml:msqrt><a svg:fill="red">')159self.assertEqual("4", soup.find("mathml:msqrt").string)160self.assertEqual("a", soup.find(attrs= { "svg:fill" : "red" }).name)161162163class TestFindAllByName(TreeTest):164"""Test ways of finding tags by tag name."""165166def setUp(self):167super(TreeTest, self).setUp()168self.tree = self.soup("""<a>First tag.</a>169<b>Second tag.</b>170<c>Third <a>Nested tag.</a> tag.</c>""")171172def test_find_all_by_tag_name(self):173# Find all the <a> tags.174self.assertSelects(175self.tree.find_all('a'), ['First tag.', 'Nested tag.'])176177def test_find_all_by_name_and_text(self):178self.assertSelects(179self.tree.find_all('a', text='First tag.'), ['First tag.'])180181self.assertSelects(182self.tree.find_all('a', text=True), ['First tag.', 'Nested tag.'])183184self.assertSelects(185self.tree.find_all('a', text=re.compile("tag")),186['First tag.', 'Nested tag.'])187188189def test_find_all_on_non_root_element(self):190# You can call find_all on any node, not just the root.191self.assertSelects(self.tree.c.find_all('a'), ['Nested tag.'])192193def test_calling_element_invokes_find_all(self):194self.assertSelects(self.tree('a'), ['First tag.', 'Nested tag.'])195196def test_find_all_by_tag_strainer(self):197self.assertSelects(198self.tree.find_all(SoupStrainer('a')),199['First tag.', 'Nested tag.'])200201def test_find_all_by_tag_names(self):202self.assertSelects(203self.tree.find_all(['a', 'b']),204['First tag.', 'Second tag.', 'Nested tag.'])205206def test_find_all_by_tag_dict(self):207self.assertSelects(208self.tree.find_all({'a' : True, 'b' : True}),209['First tag.', 'Second tag.', 'Nested tag.'])210211def test_find_all_by_tag_re(self):212self.assertSelects(213self.tree.find_all(re.compile('^[ab]$')),214['First tag.', 'Second tag.', 'Nested tag.'])215216def test_find_all_with_tags_matching_method(self):217# You can define an oracle method that determines whether218# a tag matches the search.219def id_matches_name(tag):220return tag.name == tag.get('id')221222tree = self.soup("""<a id="a">Match 1.</a>223<a id="1">Does not match.</a>224<b id="b">Match 2.</a>""")225226self.assertSelects(227tree.find_all(id_matches_name), ["Match 1.", "Match 2."])228229def test_find_with_multi_valued_attribute(self):230soup = self.soup(231"<div class='a b'>1</div><div class='a c'>2</div><div class='a d'>3</div>"232)233r1 = soup.find('div', 'a d');234r2 = soup.find('div', re.compile(r'a d'));235r3, r4 = soup.find_all('div', ['a b', 'a d']);236self.assertEqual('3', r1.string)237self.assertEqual('3', r2.string)238self.assertEqual('1', r3.string)239self.assertEqual('3', r4.string)240241242class TestFindAllByAttribute(TreeTest):243244def test_find_all_by_attribute_name(self):245# You can pass in keyword arguments to find_all to search by246# attribute.247tree = self.soup("""248<a id="first">Matching a.</a>249<a id="second">250Non-matching <b id="first">Matching b.</b>a.251</a>""")252self.assertSelects(tree.find_all(id='first'),253["Matching a.", "Matching b."])254255def test_find_all_by_utf8_attribute_value(self):256peace = "םולש".encode("utf8")257data = '<a title="םולש"></a>'.encode("utf8")258soup = self.soup(data)259self.assertEqual([soup.a], soup.find_all(title=peace))260self.assertEqual([soup.a], soup.find_all(title=peace.decode("utf8")))261self.assertEqual([soup.a], soup.find_all(title=[peace, "something else"]))262263def test_find_all_by_attribute_dict(self):264# You can pass in a dictionary as the argument 'attrs'. This265# lets you search for attributes like 'name' (a fixed argument266# to find_all) and 'class' (a reserved word in Python.)267tree = self.soup("""268<a name="name1" class="class1">Name match.</a>269<a name="name2" class="class2">Class match.</a>270<a name="name3" class="class3">Non-match.</a>271<name1>A tag called 'name1'.</name1>272""")273274# This doesn't do what you want.275self.assertSelects(tree.find_all(name='name1'),276["A tag called 'name1'."])277# This does what you want.278self.assertSelects(tree.find_all(attrs={'name' : 'name1'}),279["Name match."])280281self.assertSelects(tree.find_all(attrs={'class' : 'class2'}),282["Class match."])283284def test_find_all_by_class(self):285tree = self.soup("""286<a class="1">Class 1.</a>287<a class="2">Class 2.</a>288<b class="1">Class 1.</b>289<c class="3 4">Class 3 and 4.</c>290""")291292# Passing in the class_ keyword argument will search against293# the 'class' attribute.294self.assertSelects(tree.find_all('a', class_='1'), ['Class 1.'])295self.assertSelects(tree.find_all('c', class_='3'), ['Class 3 and 4.'])296self.assertSelects(tree.find_all('c', class_='4'), ['Class 3 and 4.'])297298# Passing in a string to 'attrs' will also search the CSS class.299self.assertSelects(tree.find_all('a', '1'), ['Class 1.'])300self.assertSelects(tree.find_all(attrs='1'), ['Class 1.', 'Class 1.'])301self.assertSelects(tree.find_all('c', '3'), ['Class 3 and 4.'])302self.assertSelects(tree.find_all('c', '4'), ['Class 3 and 4.'])303304def test_find_by_class_when_multiple_classes_present(self):305tree = self.soup("<gar class='foo bar'>Found it</gar>")306307f = tree.find_all("gar", class_=re.compile("o"))308self.assertSelects(f, ["Found it"])309310f = tree.find_all("gar", class_=re.compile("a"))311self.assertSelects(f, ["Found it"])312313# If the search fails to match the individual strings "foo" and "bar",314# it will be tried against the combined string "foo bar".315f = tree.find_all("gar", class_=re.compile("o b"))316self.assertSelects(f, ["Found it"])317318def test_find_all_with_non_dictionary_for_attrs_finds_by_class(self):319soup = self.soup("<a class='bar'>Found it</a>")320321self.assertSelects(soup.find_all("a", re.compile("ba")), ["Found it"])322323def big_attribute_value(value):324return len(value) > 3325326self.assertSelects(soup.find_all("a", big_attribute_value), [])327328def small_attribute_value(value):329return len(value) <= 3330331self.assertSelects(332soup.find_all("a", small_attribute_value), ["Found it"])333334def test_find_all_with_string_for_attrs_finds_multiple_classes(self):335soup = self.soup('<a class="foo bar"></a><a class="foo"></a>')336a, a2 = soup.find_all("a")337self.assertEqual([a, a2], soup.find_all("a", "foo"))338self.assertEqual([a], soup.find_all("a", "bar"))339340# If you specify the class as a string that contains a341# space, only that specific value will be found.342self.assertEqual([a], soup.find_all("a", class_="foo bar"))343self.assertEqual([a], soup.find_all("a", "foo bar"))344self.assertEqual([], soup.find_all("a", "bar foo"))345346def test_find_all_by_attribute_soupstrainer(self):347tree = self.soup("""348<a id="first">Match.</a>349<a id="second">Non-match.</a>""")350351strainer = SoupStrainer(attrs={'id' : 'first'})352self.assertSelects(tree.find_all(strainer), ['Match.'])353354def test_find_all_with_missing_attribute(self):355# You can pass in None as the value of an attribute to find_all.356# This will match tags that do not have that attribute set.357tree = self.soup("""<a id="1">ID present.</a>358<a>No ID present.</a>359<a id="">ID is empty.</a>""")360self.assertSelects(tree.find_all('a', id=None), ["No ID present."])361362def test_find_all_with_defined_attribute(self):363# You can pass in None as the value of an attribute to find_all.364# This will match tags that have that attribute set to any value.365tree = self.soup("""<a id="1">ID present.</a>366<a>No ID present.</a>367<a id="">ID is empty.</a>""")368self.assertSelects(369tree.find_all(id=True), ["ID present.", "ID is empty."])370371def test_find_all_with_numeric_attribute(self):372# If you search for a number, it's treated as a string.373tree = self.soup("""<a id=1>Unquoted attribute.</a>374<a id="1">Quoted attribute.</a>""")375376expected = ["Unquoted attribute.", "Quoted attribute."]377self.assertSelects(tree.find_all(id=1), expected)378self.assertSelects(tree.find_all(id="1"), expected)379380def test_find_all_with_list_attribute_values(self):381# You can pass a list of attribute values instead of just one,382# and you'll get tags that match any of the values.383tree = self.soup("""<a id="1">1</a>384<a id="2">2</a>385<a id="3">3</a>386<a>No ID.</a>""")387self.assertSelects(tree.find_all(id=["1", "3", "4"]),388["1", "3"])389390def test_find_all_with_regular_expression_attribute_value(self):391# You can pass a regular expression as an attribute value, and392# you'll get tags whose values for that attribute match the393# regular expression.394tree = self.soup("""<a id="a">One a.</a>395<a id="aa">Two as.</a>396<a id="ab">Mixed as and bs.</a>397<a id="b">One b.</a>398<a>No ID.</a>""")399400self.assertSelects(tree.find_all(id=re.compile("^a+$")),401["One a.", "Two as."])402403def test_find_by_name_and_containing_string(self):404soup = self.soup("<b>foo</b><b>bar</b><a>foo</a>")405a = soup.a406407self.assertEqual([a], soup.find_all("a", text="foo"))408self.assertEqual([], soup.find_all("a", text="bar"))409self.assertEqual([], soup.find_all("a", text="bar"))410411def test_find_by_name_and_containing_string_when_string_is_buried(self):412soup = self.soup("<a>foo</a><a><b><c>foo</c></b></a>")413self.assertEqual(soup.find_all("a"), soup.find_all("a", text="foo"))414415def test_find_by_attribute_and_containing_string(self):416soup = self.soup('<b id="1">foo</b><a id="2">foo</a>')417a = soup.a418419self.assertEqual([a], soup.find_all(id=2, text="foo"))420self.assertEqual([], soup.find_all(id=1, text="bar"))421422423class TestSmooth(TreeTest):424"""Test Tag.smooth."""425426def test_smooth(self):427soup = self.soup("<div>a</div>")428div = soup.div429div.append("b")430div.append("c")431div.append(Comment("Comment 1"))432div.append(Comment("Comment 2"))433div.append("d")434builder = self.default_builder()435span = Tag(soup, builder, 'span')436span.append('1')437span.append('2')438div.append(span)439440# At this point the tree has a bunch of adjacent441# NavigableStrings. This is normal, but it has no meaning in442# terms of HTML, so we may want to smooth things out for443# output.444445# Since the <span> tag has two children, its .string is None.446self.assertEqual(None, div.span.string)447448self.assertEqual(7, len(div.contents))449div.smooth()450self.assertEqual(5, len(div.contents))451452# The three strings at the beginning of div.contents have been453# merged into on string.454#455self.assertEqual('abc', div.contents[0])456457# The call is recursive -- the <span> tag was also smoothed.458self.assertEqual('12', div.span.string)459460# The two comments have _not_ been merged, even though461# comments are strings. Merging comments would change the462# meaning of the HTML.463self.assertEqual('Comment 1', div.contents[1])464self.assertEqual('Comment 2', div.contents[2])465466467class TestIndex(TreeTest):468"""Test Tag.index"""469def test_index(self):470tree = self.soup("""<div>471<a>Identical</a>472<b>Not identical</b>473<a>Identical</a>474475<c><d>Identical with child</d></c>476<b>Also not identical</b>477<c><d>Identical with child</d></c>478</div>""")479div = tree.div480for i, element in enumerate(div.contents):481self.assertEqual(i, div.index(element))482self.assertRaises(ValueError, tree.index, 1)483484485class TestParentOperations(TreeTest):486"""Test navigation and searching through an element's parents."""487488def setUp(self):489super(TestParentOperations, self).setUp()490self.tree = self.soup('''<ul id="empty"></ul>491<ul id="top">492<ul id="middle">493<ul id="bottom">494<b>Start here</b>495</ul>496</ul>''')497self.start = self.tree.b498499500def test_parent(self):501self.assertEqual(self.start.parent['id'], 'bottom')502self.assertEqual(self.start.parent.parent['id'], 'middle')503self.assertEqual(self.start.parent.parent.parent['id'], 'top')504505def test_parent_of_top_tag_is_soup_object(self):506top_tag = self.tree.contents[0]507self.assertEqual(top_tag.parent, self.tree)508509def test_soup_object_has_no_parent(self):510self.assertEqual(None, self.tree.parent)511512def test_find_parents(self):513self.assertSelectsIDs(514self.start.find_parents('ul'), ['bottom', 'middle', 'top'])515self.assertSelectsIDs(516self.start.find_parents('ul', id="middle"), ['middle'])517518def test_find_parent(self):519self.assertEqual(self.start.find_parent('ul')['id'], 'bottom')520self.assertEqual(self.start.find_parent('ul', id='top')['id'], 'top')521522def test_parent_of_text_element(self):523text = self.tree.find(text="Start here")524self.assertEqual(text.parent.name, 'b')525526def test_text_element_find_parent(self):527text = self.tree.find(text="Start here")528self.assertEqual(text.find_parent('ul')['id'], 'bottom')529530def test_parent_generator(self):531parents = [parent['id'] for parent in self.start.parents532if parent is not None and 'id' in parent.attrs]533self.assertEqual(parents, ['bottom', 'middle', 'top'])534535536class ProximityTest(TreeTest):537538def setUp(self):539super(TreeTest, self).setUp()540self.tree = self.soup(541'<html id="start"><head></head><body><b id="1">One</b><b id="2">Two</b><b id="3">Three</b></body></html>')542543544class TestNextOperations(ProximityTest):545546def setUp(self):547super(TestNextOperations, self).setUp()548self.start = self.tree.b549550def test_next(self):551self.assertEqual(self.start.next_element, "One")552self.assertEqual(self.start.next_element.next_element['id'], "2")553554def test_next_of_last_item_is_none(self):555last = self.tree.find(text="Three")556self.assertEqual(last.next_element, None)557558def test_next_of_root_is_none(self):559# The document root is outside the next/previous chain.560self.assertEqual(self.tree.next_element, None)561562def test_find_all_next(self):563self.assertSelects(self.start.find_all_next('b'), ["Two", "Three"])564self.start.find_all_next(id=3)565self.assertSelects(self.start.find_all_next(id=3), ["Three"])566567def test_find_next(self):568self.assertEqual(self.start.find_next('b')['id'], '2')569self.assertEqual(self.start.find_next(text="Three"), "Three")570571def test_find_next_for_text_element(self):572text = self.tree.find(text="One")573self.assertEqual(text.find_next("b").string, "Two")574self.assertSelects(text.find_all_next("b"), ["Two", "Three"])575576def test_next_generator(self):577start = self.tree.find(text="Two")578successors = [node for node in start.next_elements]579# There are two successors: the final <b> tag and its text contents.580tag, contents = successors581self.assertEqual(tag['id'], '3')582self.assertEqual(contents, "Three")583584class TestPreviousOperations(ProximityTest):585586def setUp(self):587super(TestPreviousOperations, self).setUp()588self.end = self.tree.find(text="Three")589590def test_previous(self):591self.assertEqual(self.end.previous_element['id'], "3")592self.assertEqual(self.end.previous_element.previous_element, "Two")593594def test_previous_of_first_item_is_none(self):595first = self.tree.find('html')596self.assertEqual(first.previous_element, None)597598def test_previous_of_root_is_none(self):599# The document root is outside the next/previous chain.600# XXX This is broken!601#self.assertEqual(self.tree.previous_element, None)602pass603604def test_find_all_previous(self):605# The <b> tag containing the "Three" node is the predecessor606# of the "Three" node itself, which is why "Three" shows up607# here.608self.assertSelects(609self.end.find_all_previous('b'), ["Three", "Two", "One"])610self.assertSelects(self.end.find_all_previous(id=1), ["One"])611612def test_find_previous(self):613self.assertEqual(self.end.find_previous('b')['id'], '3')614self.assertEqual(self.end.find_previous(text="One"), "One")615616def test_find_previous_for_text_element(self):617text = self.tree.find(text="Three")618self.assertEqual(text.find_previous("b").string, "Three")619self.assertSelects(620text.find_all_previous("b"), ["Three", "Two", "One"])621622def test_previous_generator(self):623start = self.tree.find(text="One")624predecessors = [node for node in start.previous_elements]625626# There are four predecessors: the <b> tag containing "One"627# the <body> tag, the <head> tag, and the <html> tag.628b, body, head, html = predecessors629self.assertEqual(b['id'], '1')630self.assertEqual(body.name, "body")631self.assertEqual(head.name, "head")632self.assertEqual(html.name, "html")633634635class SiblingTest(TreeTest):636637def setUp(self):638super(SiblingTest, self).setUp()639markup = '''<html>640<span id="1">641<span id="1.1"></span>642</span>643<span id="2">644<span id="2.1"></span>645</span>646<span id="3">647<span id="3.1"></span>648</span>649<span id="4"></span>650</html>'''651# All that whitespace looks good but makes the tests more652# difficult. Get rid of it.653markup = re.compile(r"\n\s*").sub("", markup)654self.tree = self.soup(markup)655656657class TestNextSibling(SiblingTest):658659def setUp(self):660super(TestNextSibling, self).setUp()661self.start = self.tree.find(id="1")662663def test_next_sibling_of_root_is_none(self):664self.assertEqual(self.tree.next_sibling, None)665666def test_next_sibling(self):667self.assertEqual(self.start.next_sibling['id'], '2')668self.assertEqual(self.start.next_sibling.next_sibling['id'], '3')669670# Note the difference between next_sibling and next_element.671self.assertEqual(self.start.next_element['id'], '1.1')672673def test_next_sibling_may_not_exist(self):674self.assertEqual(self.tree.html.next_sibling, None)675676nested_span = self.tree.find(id="1.1")677self.assertEqual(nested_span.next_sibling, None)678679last_span = self.tree.find(id="4")680self.assertEqual(last_span.next_sibling, None)681682def test_find_next_sibling(self):683self.assertEqual(self.start.find_next_sibling('span')['id'], '2')684685def test_next_siblings(self):686self.assertSelectsIDs(self.start.find_next_siblings("span"),687['2', '3', '4'])688689self.assertSelectsIDs(self.start.find_next_siblings(id='3'), ['3'])690691def test_next_sibling_for_text_element(self):692soup = self.soup("Foo<b>bar</b>baz")693start = soup.find(text="Foo")694self.assertEqual(start.next_sibling.name, 'b')695self.assertEqual(start.next_sibling.next_sibling, 'baz')696697self.assertSelects(start.find_next_siblings('b'), ['bar'])698self.assertEqual(start.find_next_sibling(text="baz"), "baz")699self.assertEqual(start.find_next_sibling(text="nonesuch"), None)700701702class TestPreviousSibling(SiblingTest):703704def setUp(self):705super(TestPreviousSibling, self).setUp()706self.end = self.tree.find(id="4")707708def test_previous_sibling_of_root_is_none(self):709self.assertEqual(self.tree.previous_sibling, None)710711def test_previous_sibling(self):712self.assertEqual(self.end.previous_sibling['id'], '3')713self.assertEqual(self.end.previous_sibling.previous_sibling['id'], '2')714715# Note the difference between previous_sibling and previous_element.716self.assertEqual(self.end.previous_element['id'], '3.1')717718def test_previous_sibling_may_not_exist(self):719self.assertEqual(self.tree.html.previous_sibling, None)720721nested_span = self.tree.find(id="1.1")722self.assertEqual(nested_span.previous_sibling, None)723724first_span = self.tree.find(id="1")725self.assertEqual(first_span.previous_sibling, None)726727def test_find_previous_sibling(self):728self.assertEqual(self.end.find_previous_sibling('span')['id'], '3')729730def test_previous_siblings(self):731self.assertSelectsIDs(self.end.find_previous_siblings("span"),732['3', '2', '1'])733734self.assertSelectsIDs(self.end.find_previous_siblings(id='1'), ['1'])735736def test_previous_sibling_for_text_element(self):737soup = self.soup("Foo<b>bar</b>baz")738start = soup.find(text="baz")739self.assertEqual(start.previous_sibling.name, 'b')740self.assertEqual(start.previous_sibling.previous_sibling, 'Foo')741742self.assertSelects(start.find_previous_siblings('b'), ['bar'])743self.assertEqual(start.find_previous_sibling(text="Foo"), "Foo")744self.assertEqual(start.find_previous_sibling(text="nonesuch"), None)745746747class TestTag(SoupTest):748749# Test various methods of Tag.750751def test__should_pretty_print(self):752# Test the rules about when a tag should be pretty-printed.753tag = self.soup("").new_tag("a_tag")754755# No list of whitespace-preserving tags -> pretty-print756tag._preserve_whitespace_tags = None757self.assertEqual(True, tag._should_pretty_print(0))758759# List exists but tag is not on the list -> pretty-print760tag.preserve_whitespace_tags = ["some_other_tag"]761self.assertEqual(True, tag._should_pretty_print(1))762763# Indent level is None -> don't pretty-print764self.assertEqual(False, tag._should_pretty_print(None))765766# Tag is on the whitespace-preserving list -> don't pretty-print767tag.preserve_whitespace_tags = ["some_other_tag", "a_tag"]768self.assertEqual(False, tag._should_pretty_print(1))769770771class TestTagCreation(SoupTest):772"""Test the ability to create new tags."""773def test_new_tag(self):774soup = self.soup("")775new_tag = soup.new_tag("foo", bar="baz", attrs={"name": "a name"})776self.assertTrue(isinstance(new_tag, Tag))777self.assertEqual("foo", new_tag.name)778self.assertEqual(dict(bar="baz", name="a name"), new_tag.attrs)779self.assertEqual(None, new_tag.parent)780781def test_tag_inherits_self_closing_rules_from_builder(self):782if XML_BUILDER_PRESENT:783xml_soup = BeautifulSoup("", "lxml-xml")784xml_br = xml_soup.new_tag("br")785xml_p = xml_soup.new_tag("p")786787# Both the <br> and <p> tag are empty-element, just because788# they have no contents.789self.assertEqual(b"<br/>", xml_br.encode())790self.assertEqual(b"<p/>", xml_p.encode())791792html_soup = BeautifulSoup("", "html.parser")793html_br = html_soup.new_tag("br")794html_p = html_soup.new_tag("p")795796# The HTML builder users HTML's rules about which tags are797# empty-element tags, and the new tags reflect these rules.798self.assertEqual(b"<br/>", html_br.encode())799self.assertEqual(b"<p></p>", html_p.encode())800801def test_new_string_creates_navigablestring(self):802soup = self.soup("")803s = soup.new_string("foo")804self.assertEqual("foo", s)805self.assertTrue(isinstance(s, NavigableString))806807def test_new_string_can_create_navigablestring_subclass(self):808soup = self.soup("")809s = soup.new_string("foo", Comment)810self.assertEqual("foo", s)811self.assertTrue(isinstance(s, Comment))812813class TestTreeModification(SoupTest):814815def test_attribute_modification(self):816soup = self.soup('<a id="1"></a>')817soup.a['id'] = 2818self.assertEqual(soup.decode(), self.document_for('<a id="2"></a>'))819del(soup.a['id'])820self.assertEqual(soup.decode(), self.document_for('<a></a>'))821soup.a['id2'] = 'foo'822self.assertEqual(soup.decode(), self.document_for('<a id2="foo"></a>'))823824def test_new_tag_creation(self):825builder = builder_registry.lookup('html')()826soup = self.soup("<body></body>", builder=builder)827a = Tag(soup, builder, 'a')828ol = Tag(soup, builder, 'ol')829a['href'] = 'http://foo.com/'830soup.body.insert(0, a)831soup.body.insert(1, ol)832self.assertEqual(833soup.body.encode(),834b'<body><a href="http://foo.com/"></a><ol></ol></body>')835836def test_append_to_contents_moves_tag(self):837doc = """<p id="1">Don't leave me <b>here</b>.</p>838<p id="2">Don\'t leave!</p>"""839soup = self.soup(doc)840second_para = soup.find(id='2')841bold = soup.b842843# Move the <b> tag to the end of the second paragraph.844soup.find(id='2').append(soup.b)845846# The <b> tag is now a child of the second paragraph.847self.assertEqual(bold.parent, second_para)848849self.assertEqual(850soup.decode(), self.document_for(851'<p id="1">Don\'t leave me .</p>\n'852'<p id="2">Don\'t leave!<b>here</b></p>'))853854def test_replace_with_returns_thing_that_was_replaced(self):855text = "<a></a><b><c></c></b>"856soup = self.soup(text)857a = soup.a858new_a = a.replace_with(soup.c)859self.assertEqual(a, new_a)860861def test_unwrap_returns_thing_that_was_replaced(self):862text = "<a><b></b><c></c></a>"863soup = self.soup(text)864a = soup.a865new_a = a.unwrap()866self.assertEqual(a, new_a)867868def test_replace_with_and_unwrap_give_useful_exception_when_tag_has_no_parent(self):869soup = self.soup("<a><b>Foo</b></a><c>Bar</c>")870a = soup.a871a.extract()872self.assertEqual(None, a.parent)873self.assertRaises(ValueError, a.unwrap)874self.assertRaises(ValueError, a.replace_with, soup.c)875876def test_replace_tag_with_itself(self):877text = "<a><b></b><c>Foo<d></d></c></a><a><e></e></a>"878soup = self.soup(text)879c = soup.c880soup.c.replace_with(c)881self.assertEqual(soup.decode(), self.document_for(text))882883def test_replace_tag_with_its_parent_raises_exception(self):884text = "<a><b></b></a>"885soup = self.soup(text)886self.assertRaises(ValueError, soup.b.replace_with, soup.a)887888def test_insert_tag_into_itself_raises_exception(self):889text = "<a><b></b></a>"890soup = self.soup(text)891self.assertRaises(ValueError, soup.a.insert, 0, soup.a)892893def test_insert_beautifulsoup_object_inserts_children(self):894"""Inserting one BeautifulSoup object into another actually inserts all895of its children -- you'll never combine BeautifulSoup objects.896"""897soup = self.soup("<p>And now, a word:</p><p>And we're back.</p>")898899text = "<p>p2</p><p>p3</p>"900to_insert = self.soup(text)901soup.insert(1, to_insert)902903for i in soup.descendants:904assert not isinstance(i, BeautifulSoup)905906p1, p2, p3, p4 = list(soup.children)907self.assertEqual("And now, a word:", p1.string)908self.assertEqual("p2", p2.string)909self.assertEqual("p3", p3.string)910self.assertEqual("And we're back.", p4.string)911912913def test_replace_with_maintains_next_element_throughout(self):914soup = self.soup('<p><a>one</a><b>three</b></p>')915a = soup.a916b = a.contents[0]917# Make it so the <a> tag has two text children.918a.insert(1, "two")919920# Now replace each one with the empty string.921left, right = a.contents922left.replaceWith('')923right.replaceWith('')924925# The <b> tag is still connected to the tree.926self.assertEqual("three", soup.b.string)927928def test_replace_final_node(self):929soup = self.soup("<b>Argh!</b>")930soup.find(text="Argh!").replace_with("Hooray!")931new_text = soup.find(text="Hooray!")932b = soup.b933self.assertEqual(new_text.previous_element, b)934self.assertEqual(new_text.parent, b)935self.assertEqual(new_text.previous_element.next_element, new_text)936self.assertEqual(new_text.next_element, None)937938def test_consecutive_text_nodes(self):939# A builder should never create two consecutive text nodes,940# but if you insert one next to another, Beautiful Soup will941# handle it correctly.942soup = self.soup("<a><b>Argh!</b><c></c></a>")943soup.b.insert(1, "Hooray!")944945self.assertEqual(946soup.decode(), self.document_for(947"<a><b>Argh!Hooray!</b><c></c></a>"))948949new_text = soup.find(text="Hooray!")950self.assertEqual(new_text.previous_element, "Argh!")951self.assertEqual(new_text.previous_element.next_element, new_text)952953self.assertEqual(new_text.previous_sibling, "Argh!")954self.assertEqual(new_text.previous_sibling.next_sibling, new_text)955956self.assertEqual(new_text.next_sibling, None)957self.assertEqual(new_text.next_element, soup.c)958959def test_insert_string(self):960soup = self.soup("<a></a>")961soup.a.insert(0, "bar")962soup.a.insert(0, "foo")963# The string were added to the tag.964self.assertEqual(["foo", "bar"], soup.a.contents)965# And they were converted to NavigableStrings.966self.assertEqual(soup.a.contents[0].next_element, "bar")967968def test_insert_tag(self):969builder = self.default_builder()970soup = self.soup(971"<a><b>Find</b><c>lady!</c><d></d></a>", builder=builder)972magic_tag = Tag(soup, builder, 'magictag')973magic_tag.insert(0, "the")974soup.a.insert(1, magic_tag)975976self.assertEqual(977soup.decode(), self.document_for(978"<a><b>Find</b><magictag>the</magictag><c>lady!</c><d></d></a>"))979980# Make sure all the relationships are hooked up correctly.981b_tag = soup.b982self.assertEqual(b_tag.next_sibling, magic_tag)983self.assertEqual(magic_tag.previous_sibling, b_tag)984985find = b_tag.find(text="Find")986self.assertEqual(find.next_element, magic_tag)987self.assertEqual(magic_tag.previous_element, find)988989c_tag = soup.c990self.assertEqual(magic_tag.next_sibling, c_tag)991self.assertEqual(c_tag.previous_sibling, magic_tag)992993the = magic_tag.find(text="the")994self.assertEqual(the.parent, magic_tag)995self.assertEqual(the.next_element, c_tag)996self.assertEqual(c_tag.previous_element, the)997998def test_append_child_thats_already_at_the_end(self):999data = "<a><b></b></a>"1000soup = self.soup(data)1001soup.a.append(soup.b)1002self.assertEqual(data, soup.decode())10031004def test_extend(self):1005data = "<a><b><c><d><e><f><g></g></f></e></d></c></b></a>"1006soup = self.soup(data)1007l = [soup.g, soup.f, soup.e, soup.d, soup.c, soup.b]1008soup.a.extend(l)1009self.assertEqual("<a><g></g><f></f><e></e><d></d><c></c><b></b></a>", soup.decode())10101011def test_move_tag_to_beginning_of_parent(self):1012data = "<a><b></b><c></c><d></d></a>"1013soup = self.soup(data)1014soup.a.insert(0, soup.d)1015self.assertEqual("<a><d></d><b></b><c></c></a>", soup.decode())10161017def test_insert_works_on_empty_element_tag(self):1018# This is a little strange, since most HTML parsers don't allow1019# markup like this to come through. But in general, we don't1020# know what the parser would or wouldn't have allowed, so1021# I'm letting this succeed for now.1022soup = self.soup("<br/>")1023soup.br.insert(1, "Contents")1024self.assertEqual(str(soup.br), "<br>Contents</br>")10251026def test_insert_before(self):1027soup = self.soup("<a>foo</a><b>bar</b>")1028soup.b.insert_before("BAZ")1029soup.a.insert_before("QUUX")1030self.assertEqual(1031soup.decode(), self.document_for("QUUX<a>foo</a>BAZ<b>bar</b>"))10321033soup.a.insert_before(soup.b)1034self.assertEqual(1035soup.decode(), self.document_for("QUUX<b>bar</b><a>foo</a>BAZ"))10361037# Can't insert an element before itself.1038b = soup.b1039self.assertRaises(ValueError, b.insert_before, b)10401041# Can't insert before if an element has no parent.1042b.extract()1043self.assertRaises(ValueError, b.insert_before, "nope")10441045# Can insert an identical element1046soup = self.soup("<a>")1047soup.a.insert_before(soup.new_tag("a"))10481049def test_insert_multiple_before(self):1050soup = self.soup("<a>foo</a><b>bar</b>")1051soup.b.insert_before("BAZ", " ", "QUUX")1052soup.a.insert_before("QUUX", " ", "BAZ")1053self.assertEqual(1054soup.decode(), self.document_for("QUUX BAZ<a>foo</a>BAZ QUUX<b>bar</b>"))10551056soup.a.insert_before(soup.b, "FOO")1057self.assertEqual(1058soup.decode(), self.document_for("QUUX BAZ<b>bar</b>FOO<a>foo</a>BAZ QUUX"))10591060def test_insert_after(self):1061soup = self.soup("<a>foo</a><b>bar</b>")1062soup.b.insert_after("BAZ")1063soup.a.insert_after("QUUX")1064self.assertEqual(1065soup.decode(), self.document_for("<a>foo</a>QUUX<b>bar</b>BAZ"))1066soup.b.insert_after(soup.a)1067self.assertEqual(1068soup.decode(), self.document_for("QUUX<b>bar</b><a>foo</a>BAZ"))10691070# Can't insert an element after itself.1071b = soup.b1072self.assertRaises(ValueError, b.insert_after, b)10731074# Can't insert after if an element has no parent.1075b.extract()1076self.assertRaises(ValueError, b.insert_after, "nope")10771078# Can insert an identical element1079soup = self.soup("<a>")1080soup.a.insert_before(soup.new_tag("a"))10811082def test_insert_multiple_after(self):1083soup = self.soup("<a>foo</a><b>bar</b>")1084soup.b.insert_after("BAZ", " ", "QUUX")1085soup.a.insert_after("QUUX", " ", "BAZ")1086self.assertEqual(1087soup.decode(), self.document_for("<a>foo</a>QUUX BAZ<b>bar</b>BAZ QUUX"))1088soup.b.insert_after(soup.a, "FOO ")1089self.assertEqual(1090soup.decode(), self.document_for("QUUX BAZ<b>bar</b><a>foo</a>FOO BAZ QUUX"))10911092def test_insert_after_raises_exception_if_after_has_no_meaning(self):1093soup = self.soup("")1094tag = soup.new_tag("a")1095string = soup.new_string("")1096self.assertRaises(ValueError, string.insert_after, tag)1097self.assertRaises(NotImplementedError, soup.insert_after, tag)1098self.assertRaises(ValueError, tag.insert_after, tag)10991100def test_insert_before_raises_notimplementederror_if_before_has_no_meaning(self):1101soup = self.soup("")1102tag = soup.new_tag("a")1103string = soup.new_string("")1104self.assertRaises(ValueError, string.insert_before, tag)1105self.assertRaises(NotImplementedError, soup.insert_before, tag)1106self.assertRaises(ValueError, tag.insert_before, tag)11071108def test_replace_with(self):1109soup = self.soup(1110"<p>There's <b>no</b> business like <b>show</b> business</p>")1111no, show = soup.find_all('b')1112show.replace_with(no)1113self.assertEqual(1114soup.decode(),1115self.document_for(1116"<p>There's business like <b>no</b> business</p>"))11171118self.assertEqual(show.parent, None)1119self.assertEqual(no.parent, soup.p)1120self.assertEqual(no.next_element, "no")1121self.assertEqual(no.next_sibling, " business")11221123def test_replace_first_child(self):1124data = "<a><b></b><c></c></a>"1125soup = self.soup(data)1126soup.b.replace_with(soup.c)1127self.assertEqual("<a><c></c></a>", soup.decode())11281129def test_replace_last_child(self):1130data = "<a><b></b><c></c></a>"1131soup = self.soup(data)1132soup.c.replace_with(soup.b)1133self.assertEqual("<a><b></b></a>", soup.decode())11341135def test_nested_tag_replace_with(self):1136soup = self.soup(1137"""<a>We<b>reserve<c>the</c><d>right</d></b></a><e>to<f>refuse</f><g>service</g></e>""")11381139# Replace the entire <b> tag and its contents ("reserve the1140# right") with the <f> tag ("refuse").1141remove_tag = soup.b1142move_tag = soup.f1143remove_tag.replace_with(move_tag)11441145self.assertEqual(1146soup.decode(), self.document_for(1147"<a>We<f>refuse</f></a><e>to<g>service</g></e>"))11481149# The <b> tag is now an orphan.1150self.assertEqual(remove_tag.parent, None)1151self.assertEqual(remove_tag.find(text="right").next_element, None)1152self.assertEqual(remove_tag.previous_element, None)1153self.assertEqual(remove_tag.next_sibling, None)1154self.assertEqual(remove_tag.previous_sibling, None)11551156# The <f> tag is now connected to the <a> tag.1157self.assertEqual(move_tag.parent, soup.a)1158self.assertEqual(move_tag.previous_element, "We")1159self.assertEqual(move_tag.next_element.next_element, soup.e)1160self.assertEqual(move_tag.next_sibling, None)11611162# The gap where the <f> tag used to be has been mended, and1163# the word "to" is now connected to the <g> tag.1164to_text = soup.find(text="to")1165g_tag = soup.g1166self.assertEqual(to_text.next_element, g_tag)1167self.assertEqual(to_text.next_sibling, g_tag)1168self.assertEqual(g_tag.previous_element, to_text)1169self.assertEqual(g_tag.previous_sibling, to_text)11701171def test_unwrap(self):1172tree = self.soup("""1173<p>Unneeded <em>formatting</em> is unneeded</p>1174""")1175tree.em.unwrap()1176self.assertEqual(tree.em, None)1177self.assertEqual(tree.p.text, "Unneeded formatting is unneeded")11781179def test_wrap(self):1180soup = self.soup("I wish I was bold.")1181value = soup.string.wrap(soup.new_tag("b"))1182self.assertEqual(value.decode(), "<b>I wish I was bold.</b>")1183self.assertEqual(1184soup.decode(), self.document_for("<b>I wish I was bold.</b>"))11851186def test_wrap_extracts_tag_from_elsewhere(self):1187soup = self.soup("<b></b>I wish I was bold.")1188soup.b.next_sibling.wrap(soup.b)1189self.assertEqual(1190soup.decode(), self.document_for("<b>I wish I was bold.</b>"))11911192def test_wrap_puts_new_contents_at_the_end(self):1193soup = self.soup("<b>I like being bold.</b>I wish I was bold.")1194soup.b.next_sibling.wrap(soup.b)1195self.assertEqual(2, len(soup.b.contents))1196self.assertEqual(1197soup.decode(), self.document_for(1198"<b>I like being bold.I wish I was bold.</b>"))11991200def test_extract(self):1201soup = self.soup(1202'<html><body>Some content. <div id="nav">Nav crap</div> More content.</body></html>')12031204self.assertEqual(len(soup.body.contents), 3)1205extracted = soup.find(id="nav").extract()12061207self.assertEqual(1208soup.decode(), "<html><body>Some content. More content.</body></html>")1209self.assertEqual(extracted.decode(), '<div id="nav">Nav crap</div>')12101211# The extracted tag is now an orphan.1212self.assertEqual(len(soup.body.contents), 2)1213self.assertEqual(extracted.parent, None)1214self.assertEqual(extracted.previous_element, None)1215self.assertEqual(extracted.next_element.next_element, None)12161217# The gap where the extracted tag used to be has been mended.1218content_1 = soup.find(text="Some content. ")1219content_2 = soup.find(text=" More content.")1220self.assertEqual(content_1.next_element, content_2)1221self.assertEqual(content_1.next_sibling, content_2)1222self.assertEqual(content_2.previous_element, content_1)1223self.assertEqual(content_2.previous_sibling, content_1)12241225def test_extract_distinguishes_between_identical_strings(self):1226soup = self.soup("<a>foo</a><b>bar</b>")1227foo_1 = soup.a.string1228bar_1 = soup.b.string1229foo_2 = soup.new_string("foo")1230bar_2 = soup.new_string("bar")1231soup.a.append(foo_2)1232soup.b.append(bar_2)12331234# Now there are two identical strings in the <a> tag, and two1235# in the <b> tag. Let's remove the first "foo" and the second1236# "bar".1237foo_1.extract()1238bar_2.extract()1239self.assertEqual(foo_2, soup.a.string)1240self.assertEqual(bar_2, soup.b.string)12411242def test_extract_multiples_of_same_tag(self):1243soup = self.soup("""1244<html>1245<head>1246<script>foo</script>1247</head>1248<body>1249<script>bar</script>1250<a></a>1251</body>1252<script>baz</script>1253</html>""")1254[soup.script.extract() for i in soup.find_all("script")]1255self.assertEqual("<body>\n\n<a></a>\n</body>", str(soup.body))125612571258def test_extract_works_when_element_is_surrounded_by_identical_strings(self):1259soup = self.soup(1260'<html>\n'1261'<body>hi</body>\n'1262'</html>')1263soup.find('body').extract()1264self.assertEqual(None, soup.find('body'))126512661267def test_clear(self):1268"""Tag.clear()"""1269soup = self.soup("<p><a>String <em>Italicized</em></a> and another</p>")1270# clear using extract()1271a = soup.a1272soup.p.clear()1273self.assertEqual(len(soup.p.contents), 0)1274self.assertTrue(hasattr(a, "contents"))12751276# clear using decompose()1277em = a.em1278a.clear(decompose=True)1279self.assertEqual(0, len(em.contents))128012811282def test_decompose(self):1283# Test PageElement.decompose() and PageElement.decomposed1284soup = self.soup("<p><a>String <em>Italicized</em></a></p><p>Another para</p>")1285p1, p2 = soup.find_all('p')1286a = p1.a1287text = p1.em.string1288for i in [p1, p2, a, text]:1289self.assertEqual(False, i.decomposed)12901291# This sets p1 and everything beneath it to decomposed.1292p1.decompose()1293for i in [p1, a, text]:1294self.assertEqual(True, i.decomposed)1295# p2 is unaffected.1296self.assertEqual(False, p2.decomposed)12971298def test_string_set(self):1299"""Tag.string = 'string'"""1300soup = self.soup("<a></a> <b><c></c></b>")1301soup.a.string = "foo"1302self.assertEqual(soup.a.contents, ["foo"])1303soup.b.string = "bar"1304self.assertEqual(soup.b.contents, ["bar"])13051306def test_string_set_does_not_affect_original_string(self):1307soup = self.soup("<a><b>foo</b><c>bar</c>")1308soup.b.string = soup.c.string1309self.assertEqual(soup.a.encode(), b"<a><b>bar</b><c>bar</c></a>")13101311def test_set_string_preserves_class_of_string(self):1312soup = self.soup("<a></a>")1313cdata = CData("foo")1314soup.a.string = cdata1315self.assertTrue(isinstance(soup.a.string, CData))13161317class TestElementObjects(SoupTest):1318"""Test various features of element objects."""13191320def test_len(self):1321"""The length of an element is its number of children."""1322soup = self.soup("<top>1<b>2</b>3</top>")13231324# The BeautifulSoup object itself contains one element: the1325# <top> tag.1326self.assertEqual(len(soup.contents), 1)1327self.assertEqual(len(soup), 1)13281329# The <top> tag contains three elements: the text node "1", the1330# <b> tag, and the text node "3".1331self.assertEqual(len(soup.top), 3)1332self.assertEqual(len(soup.top.contents), 3)13331334def test_member_access_invokes_find(self):1335"""Accessing a Python member .foo invokes find('foo')"""1336soup = self.soup('<b><i></i></b>')1337self.assertEqual(soup.b, soup.find('b'))1338self.assertEqual(soup.b.i, soup.find('b').find('i'))1339self.assertEqual(soup.a, None)13401341def test_deprecated_member_access(self):1342soup = self.soup('<b><i></i></b>')1343with warnings.catch_warnings(record=True) as w:1344tag = soup.bTag1345self.assertEqual(soup.b, tag)1346self.assertEqual(1347'.bTag is deprecated, use .find("b") instead. If you really were looking for a tag called bTag, use .find("bTag")',1348str(w[0].message))13491350def test_has_attr(self):1351"""has_attr() checks for the presence of an attribute.13521353Please note note: has_attr() is different from1354__in__. has_attr() checks the tag's attributes and __in__1355checks the tag's chidlren.1356"""1357soup = self.soup("<foo attr='bar'>")1358self.assertTrue(soup.foo.has_attr('attr'))1359self.assertFalse(soup.foo.has_attr('attr2'))136013611362def test_attributes_come_out_in_alphabetical_order(self):1363markup = '<b a="1" z="5" m="3" f="2" y="4"></b>'1364self.assertSoupEquals(markup, '<b a="1" f="2" m="3" y="4" z="5"></b>')13651366def test_string(self):1367# A tag that contains only a text node makes that node1368# available as .string.1369soup = self.soup("<b>foo</b>")1370self.assertEqual(soup.b.string, 'foo')13711372def test_empty_tag_has_no_string(self):1373# A tag with no children has no .stirng.1374soup = self.soup("<b></b>")1375self.assertEqual(soup.b.string, None)13761377def test_tag_with_multiple_children_has_no_string(self):1378# A tag with no children has no .string.1379soup = self.soup("<a>foo<b></b><b></b></b>")1380self.assertEqual(soup.b.string, None)13811382soup = self.soup("<a>foo<b></b>bar</b>")1383self.assertEqual(soup.b.string, None)13841385# Even if all the children are strings, due to trickery,1386# it won't work--but this would be a good optimization.1387soup = self.soup("<a>foo</b>")1388soup.a.insert(1, "bar")1389self.assertEqual(soup.a.string, None)13901391def test_tag_with_recursive_string_has_string(self):1392# A tag with a single child which has a .string inherits that1393# .string.1394soup = self.soup("<a><b>foo</b></a>")1395self.assertEqual(soup.a.string, "foo")1396self.assertEqual(soup.string, "foo")13971398def test_lack_of_string(self):1399"""Only a tag containing a single text node has a .string."""1400soup = self.soup("<b>f<i>e</i>o</b>")1401self.assertFalse(soup.b.string)14021403soup = self.soup("<b></b>")1404self.assertFalse(soup.b.string)14051406def test_all_text(self):1407"""Tag.text and Tag.get_text(sep=u"") -> all child text, concatenated"""1408soup = self.soup("<a>a<b>r</b> <r> t </r></a>")1409self.assertEqual(soup.a.text, "ar t ")1410self.assertEqual(soup.a.get_text(strip=True), "art")1411self.assertEqual(soup.a.get_text(","), "a,r, , t ")1412self.assertEqual(soup.a.get_text(",", strip=True), "a,r,t")14131414def test_get_text_ignores_special_string_containers(self):1415soup = self.soup("foo<!--IGNORE-->bar")1416self.assertEqual(soup.get_text(), "foobar")14171418self.assertEqual(1419soup.get_text(types=(NavigableString, Comment)), "fooIGNOREbar")1420self.assertEqual(1421soup.get_text(types=None), "fooIGNOREbar")14221423soup = self.soup("foo<style>CSS</style><script>Javascript</script>bar")1424self.assertEqual(soup.get_text(), "foobar")14251426def test_all_strings_ignores_special_string_containers(self):1427soup = self.soup("foo<!--IGNORE-->bar")1428self.assertEqual(['foo', 'bar'], list(soup.strings))14291430soup = self.soup("foo<style>CSS</style><script>Javascript</script>bar")1431self.assertEqual(['foo', 'bar'], list(soup.strings))143214331434class TestCDAtaListAttributes(SoupTest):14351436"""Testing cdata-list attributes like 'class'.1437"""1438def test_single_value_becomes_list(self):1439soup = self.soup("<a class='foo'>")1440self.assertEqual(["foo"],soup.a['class'])14411442def test_multiple_values_becomes_list(self):1443soup = self.soup("<a class='foo bar'>")1444self.assertEqual(["foo", "bar"], soup.a['class'])14451446def test_multiple_values_separated_by_weird_whitespace(self):1447soup = self.soup("<a class='foo\tbar\nbaz'>")1448self.assertEqual(["foo", "bar", "baz"],soup.a['class'])14491450def test_attributes_joined_into_string_on_output(self):1451soup = self.soup("<a class='foo\tbar'>")1452self.assertEqual(b'<a class="foo bar"></a>', soup.a.encode())14531454def test_get_attribute_list(self):1455soup = self.soup("<a id='abc def'>")1456self.assertEqual(['abc def'], soup.a.get_attribute_list('id'))14571458def test_accept_charset(self):1459soup = self.soup('<form accept-charset="ISO-8859-1 UTF-8">')1460self.assertEqual(['ISO-8859-1', 'UTF-8'], soup.form['accept-charset'])14611462def test_cdata_attribute_applying_only_to_one_tag(self):1463data = '<a accept-charset="ISO-8859-1 UTF-8"></a>'1464soup = self.soup(data)1465# We saw in another test that accept-charset is a cdata-list1466# attribute for the <form> tag. But it's not a cdata-list1467# attribute for any other tag.1468self.assertEqual('ISO-8859-1 UTF-8', soup.a['accept-charset'])14691470def test_string_has_immutable_name_property(self):1471string = self.soup("s").string1472self.assertEqual(None, string.name)1473def t():1474string.name = 'foo'1475self.assertRaises(AttributeError, t)14761477class TestPersistence(SoupTest):1478"Testing features like pickle and deepcopy."14791480def setUp(self):1481super(TestPersistence, self).setUp()1482self.page = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"1483"http://www.w3.org/TR/REC-html40/transitional.dtd">1484<html>1485<head>1486<meta http-equiv="Content-Type" content="text/html; charset=utf-8">1487<title>Beautiful Soup: We called him Tortoise because he taught us.</title>1488<link rev="made" href="mailto:[email protected]">1489<meta name="Description" content="Beautiful Soup: an HTML parser optimized for screen-scraping.">1490<meta name="generator" content="Markov Approximation 1.4 (module: leonardr)">1491<meta name="author" content="Leonard Richardson">1492</head>1493<body>1494<a href="foo">foo</a>1495<a href="foo"><b>bar</b></a>1496</body>1497</html>"""1498self.tree = self.soup(self.page)14991500def test_pickle_and_unpickle_identity(self):1501# Pickling a tree, then unpickling it, yields a tree identical1502# to the original.1503dumped = pickle.dumps(self.tree, 2)1504loaded = pickle.loads(dumped)1505self.assertEqual(loaded.__class__, BeautifulSoup)1506self.assertEqual(loaded.decode(), self.tree.decode())15071508def test_deepcopy_identity(self):1509# Making a deepcopy of a tree yields an identical tree.1510copied = copy.deepcopy(self.tree)1511self.assertEqual(copied.decode(), self.tree.decode())15121513def test_copy_preserves_encoding(self):1514soup = BeautifulSoup(b'<p> </p>', 'html.parser')1515encoding = soup.original_encoding1516copy = soup.__copy__()1517self.assertEqual("<p> </p>", str(copy))1518self.assertEqual(encoding, copy.original_encoding)15191520def test_copy_preserves_builder_information(self):15211522tag = self.soup('<p></p>').p15231524# Simulate a tag obtained from a source file.1525tag.sourceline = 101526tag.sourcepos = 3315271528copied = tag.__copy__()15291530# The TreeBuilder object is no longer availble, but information1531# obtained from it gets copied over to the new Tag object.1532self.assertEqual(tag.sourceline, copied.sourceline)1533self.assertEqual(tag.sourcepos, copied.sourcepos)1534self.assertEqual(1535tag.can_be_empty_element, copied.can_be_empty_element1536)1537self.assertEqual(1538tag.cdata_list_attributes, copied.cdata_list_attributes1539)1540self.assertEqual(1541tag.preserve_whitespace_tags, copied.preserve_whitespace_tags1542)154315441545def test_unicode_pickle(self):1546# A tree containing Unicode characters can be pickled.1547html = "<b>\N{SNOWMAN}</b>"1548soup = self.soup(html)1549dumped = pickle.dumps(soup, pickle.HIGHEST_PROTOCOL)1550loaded = pickle.loads(dumped)1551self.assertEqual(loaded.decode(), soup.decode())15521553def test_copy_navigablestring_is_not_attached_to_tree(self):1554html = "<b>Foo<a></a></b><b>Bar</b>"1555soup = self.soup(html)1556s1 = soup.find(string="Foo")1557s2 = copy.copy(s1)1558self.assertEqual(s1, s2)1559self.assertEqual(None, s2.parent)1560self.assertEqual(None, s2.next_element)1561self.assertNotEqual(None, s1.next_sibling)1562self.assertEqual(None, s2.next_sibling)1563self.assertEqual(None, s2.previous_element)15641565def test_copy_navigablestring_subclass_has_same_type(self):1566html = "<b><!--Foo--></b>"1567soup = self.soup(html)1568s1 = soup.string1569s2 = copy.copy(s1)1570self.assertEqual(s1, s2)1571self.assertTrue(isinstance(s2, Comment))15721573def test_copy_entire_soup(self):1574html = "<div><b>Foo<a></a></b><b>Bar</b></div>end"1575soup = self.soup(html)1576soup_copy = copy.copy(soup)1577self.assertEqual(soup, soup_copy)15781579def test_copy_tag_copies_contents(self):1580html = "<div><b>Foo<a></a></b><b>Bar</b></div>end"1581soup = self.soup(html)1582div = soup.div1583div_copy = copy.copy(div)15841585# The two tags look the same, and evaluate to equal.1586self.assertEqual(str(div), str(div_copy))1587self.assertEqual(div, div_copy)15881589# But they're not the same object.1590self.assertFalse(div is div_copy)15911592# And they don't have the same relation to the parse tree. The1593# copy is not associated with a parse tree at all.1594self.assertEqual(None, div_copy.parent)1595self.assertEqual(None, div_copy.previous_element)1596self.assertEqual(None, div_copy.find(string='Bar').next_element)1597self.assertNotEqual(None, div.find(string='Bar').next_element)15981599class TestSubstitutions(SoupTest):16001601def test_default_formatter_is_minimal(self):1602markup = "<b><<Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></b>"1603soup = self.soup(markup)1604decoded = soup.decode(formatter="minimal")1605# The < is converted back into < but the e-with-acute is left alone.1606self.assertEqual(1607decoded,1608self.document_for(1609"<b><<Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></b>"))16101611def test_formatter_html(self):1612markup = "<br><b><<Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></b>"1613soup = self.soup(markup)1614decoded = soup.decode(formatter="html")1615self.assertEqual(1616decoded,1617self.document_for("<br/><b><<Sacré bleu!>></b>"))16181619def test_formatter_html5(self):1620markup = "<br><b><<Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></b>"1621soup = self.soup(markup)1622decoded = soup.decode(formatter="html5")1623self.assertEqual(1624decoded,1625self.document_for("<br><b><<Sacré bleu!>></b>"))16261627def test_formatter_minimal(self):1628markup = "<b><<Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></b>"1629soup = self.soup(markup)1630decoded = soup.decode(formatter="minimal")1631# The < is converted back into < but the e-with-acute is left alone.1632self.assertEqual(1633decoded,1634self.document_for(1635"<b><<Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></b>"))16361637def test_formatter_null(self):1638markup = "<b><<Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></b>"1639soup = self.soup(markup)1640decoded = soup.decode(formatter=None)1641# Neither the angle brackets nor the e-with-acute are converted.1642# This is not valid HTML, but it's what the user wanted.1643self.assertEqual(decoded,1644self.document_for("<b><<Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></b>"))16451646def test_formatter_custom(self):1647markup = "<b><foo></b><b>bar</b><br/>"1648soup = self.soup(markup)1649decoded = soup.decode(formatter = lambda x: x.upper())1650# Instead of normal entity conversion code, the custom1651# callable is called on every string.1652self.assertEqual(1653decoded,1654self.document_for("<b><FOO></b><b>BAR</b><br/>"))16551656def test_formatter_is_run_on_attribute_values(self):1657markup = '<a href="http://a.com?a=b&c=é">e</a>'1658soup = self.soup(markup)1659a = soup.a16601661expect_minimal = '<a href="http://a.com?a=b&c=é">e</a>'16621663self.assertEqual(expect_minimal, a.decode())1664self.assertEqual(expect_minimal, a.decode(formatter="minimal"))16651666expect_html = '<a href="http://a.com?a=b&c=é">e</a>'1667self.assertEqual(expect_html, a.decode(formatter="html"))16681669self.assertEqual(markup, a.decode(formatter=None))1670expect_upper = '<a href="HTTP://A.COM?A=B&C=É">E</a>'1671self.assertEqual(expect_upper, a.decode(formatter=lambda x: x.upper()))16721673def test_formatter_skips_script_tag_for_html_documents(self):1674doc = """1675<script type="text/javascript">1676console.log("< < hey > > ");1677</script>1678"""1679encoded = BeautifulSoup(doc, 'html.parser').encode()1680self.assertTrue(b"< < hey > >" in encoded)16811682def test_formatter_skips_style_tag_for_html_documents(self):1683doc = """1684<style type="text/css">1685console.log("< < hey > > ");1686</style>1687"""1688encoded = BeautifulSoup(doc, 'html.parser').encode()1689self.assertTrue(b"< < hey > >" in encoded)16901691def test_prettify_leaves_preformatted_text_alone(self):1692soup = self.soup("<div> foo <pre> \tbar\n \n </pre> baz <textarea> eee\nfff\t</textarea></div>")1693# Everything outside the <pre> tag is reformatted, but everything1694# inside is left alone.1695self.assertEqual(1696'<div>\n foo\n <pre> \tbar\n \n </pre>\n baz\n <textarea> eee\nfff\t</textarea>\n</div>',1697soup.div.prettify())16981699def test_prettify_accepts_formatter_function(self):1700soup = BeautifulSoup("<html><body>foo</body></html>", 'html.parser')1701pretty = soup.prettify(formatter = lambda x: x.upper())1702self.assertTrue("FOO" in pretty)17031704def test_prettify_outputs_unicode_by_default(self):1705soup = self.soup("<a></a>")1706self.assertEqual(str, type(soup.prettify()))17071708def test_prettify_can_encode_data(self):1709soup = self.soup("<a></a>")1710self.assertEqual(bytes, type(soup.prettify("utf-8")))17111712def test_html_entity_substitution_off_by_default(self):1713markup = "<b>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</b>"1714soup = self.soup(markup)1715encoded = soup.b.encode("utf-8")1716self.assertEqual(encoded, markup.encode('utf-8'))17171718def test_encoding_substitution(self):1719# Here's the <meta> tag saying that a document is1720# encoded in Shift-JIS.1721meta_tag = ('<meta content="text/html; charset=x-sjis" '1722'http-equiv="Content-type"/>')1723soup = self.soup(meta_tag)17241725# Parse the document, and the charset apprears unchanged.1726self.assertEqual(soup.meta['content'], 'text/html; charset=x-sjis')17271728# Encode the document into some encoding, and the encoding is1729# substituted into the meta tag.1730utf_8 = soup.encode("utf-8")1731self.assertTrue(b"charset=utf-8" in utf_8)17321733euc_jp = soup.encode("euc_jp")1734self.assertTrue(b"charset=euc_jp" in euc_jp)17351736shift_jis = soup.encode("shift-jis")1737self.assertTrue(b"charset=shift-jis" in shift_jis)17381739utf_16_u = soup.encode("utf-16").decode("utf-16")1740self.assertTrue("charset=utf-16" in utf_16_u)17411742def test_encoding_substitution_doesnt_happen_if_tag_is_strained(self):1743markup = ('<head><meta content="text/html; charset=x-sjis" '1744'http-equiv="Content-type"/></head><pre>foo</pre>')17451746# Beautiful Soup used to try to rewrite the meta tag even if the1747# meta tag got filtered out by the strainer. This test makes1748# sure that doesn't happen.1749strainer = SoupStrainer('pre')1750soup = self.soup(markup, parse_only=strainer)1751self.assertEqual(soup.contents[0].name, 'pre')17521753class TestEncoding(SoupTest):1754"""Test the ability to encode objects into strings."""17551756def test_unicode_string_can_be_encoded(self):1757html = "<b>\N{SNOWMAN}</b>"1758soup = self.soup(html)1759self.assertEqual(soup.b.string.encode("utf-8"),1760"\N{SNOWMAN}".encode("utf-8"))17611762def test_tag_containing_unicode_string_can_be_encoded(self):1763html = "<b>\N{SNOWMAN}</b>"1764soup = self.soup(html)1765self.assertEqual(1766soup.b.encode("utf-8"), html.encode("utf-8"))17671768def test_encoding_substitutes_unrecognized_characters_by_default(self):1769html = "<b>\N{SNOWMAN}</b>"1770soup = self.soup(html)1771self.assertEqual(soup.b.encode("ascii"), b"<b>☃</b>")17721773def test_encoding_can_be_made_strict(self):1774html = "<b>\N{SNOWMAN}</b>"1775soup = self.soup(html)1776self.assertRaises(1777UnicodeEncodeError, soup.encode, "ascii", errors="strict")17781779def test_decode_contents(self):1780html = "<b>\N{SNOWMAN}</b>"1781soup = self.soup(html)1782self.assertEqual("\N{SNOWMAN}", soup.b.decode_contents())17831784def test_encode_contents(self):1785html = "<b>\N{SNOWMAN}</b>"1786soup = self.soup(html)1787self.assertEqual(1788"\N{SNOWMAN}".encode("utf8"), soup.b.encode_contents(1789encoding="utf8"))17901791def test_deprecated_renderContents(self):1792html = "<b>\N{SNOWMAN}</b>"1793soup = self.soup(html)1794self.assertEqual(1795"\N{SNOWMAN}".encode("utf8"), soup.b.renderContents())17961797def test_repr(self):1798html = "<b>\N{SNOWMAN}</b>"1799soup = self.soup(html)1800if PY3K:1801self.assertEqual(html, repr(soup))1802else:1803self.assertEqual(b'<b>\\u2603</b>', repr(soup))18041805class TestFormatter(SoupTest):18061807def test_default_attributes(self):1808# Test the default behavior of Formatter.attributes().1809formatter = Formatter()1810tag = Tag(name="tag")1811tag['b'] = 11812tag['a'] = 218131814# Attributes come out sorted by name. In Python 3, attributes1815# normally come out of a dictionary in the order they were1816# added.1817self.assertEqual([('a', 2), ('b', 1)], formatter.attributes(tag))18181819# This works even if Tag.attrs is None, though this shouldn't1820# normally happen.1821tag.attrs = None1822self.assertEqual([], formatter.attributes(tag))18231824def test_sort_attributes(self):1825# Test the ability to override Formatter.attributes() to,1826# e.g., disable the normal sorting of attributes.1827class UnsortedFormatter(Formatter):1828def attributes(self, tag):1829self.called_with = tag1830for k, v in sorted(tag.attrs.items()):1831if k == 'ignore':1832continue1833yield k,v18341835soup = self.soup('<p cval="1" aval="2" ignore="ignored"></p>')1836formatter = UnsortedFormatter()1837decoded = soup.decode(formatter=formatter)18381839# attributes() was called on the <p> tag. It filtered out one1840# attribute and sorted the other two.1841self.assertEqual(formatter.called_with, soup.p)1842self.assertEqual('<p aval="2" cval="1"></p>', decoded)184318441845class TestNavigableStringSubclasses(SoupTest):18461847def test_cdata(self):1848# None of the current builders turn CDATA sections into CData1849# objects, but you can create them manually.1850soup = self.soup("")1851cdata = CData("foo")1852soup.insert(1, cdata)1853self.assertEqual(str(soup), "<![CDATA[foo]]>")1854self.assertEqual(soup.find(text="foo"), "foo")1855self.assertEqual(soup.contents[0], "foo")18561857def test_cdata_is_never_formatted(self):1858"""Text inside a CData object is passed into the formatter.18591860But the return value is ignored.1861"""18621863self.count = 01864def increment(*args):1865self.count += 11866return "BITTER FAILURE"18671868soup = self.soup("")1869cdata = CData("<><><>")1870soup.insert(1, cdata)1871self.assertEqual(1872b"<![CDATA[<><><>]]>", soup.encode(formatter=increment))1873self.assertEqual(1, self.count)18741875def test_doctype_ends_in_newline(self):1876# Unlike other NavigableString subclasses, a DOCTYPE always ends1877# in a newline.1878doctype = Doctype("foo")1879soup = self.soup("")1880soup.insert(1, doctype)1881self.assertEqual(soup.encode(), b"<!DOCTYPE foo>\n")18821883def test_declaration(self):1884d = Declaration("foo")1885self.assertEqual("<?foo?>", d.output_ready())18861887def test_default_string_containers(self):1888# In some cases, we use different NavigableString subclasses for1889# the same text in different tags.1890soup = self.soup(1891"<div>text</div><script>text</script><style>text</style>"1892)1893self.assertEqual(1894[NavigableString, Script, Stylesheet],1895[x.__class__ for x in soup.find_all(text=True)]1896)18971898# The TemplateString is a little unusual because it's generally found1899# _inside_ children of a <template> element, not a direct child of the1900# <template> element.1901soup = self.soup(1902"<template>Some text<p>In a tag</p></template>Some text outside"1903)1904assert all(isinstance(x, TemplateString) for x in soup.template.strings)19051906# Once the <template> tag closed, we went back to using1907# NavigableString.1908outside = soup.template.next_sibling1909assert isinstance(outside, NavigableString)1910assert not isinstance(outside, TemplateString)19111912class TestSoupSelector(TreeTest):19131914HTML = """1915<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"1916"http://www.w3.org/TR/html4/strict.dtd">1917<html>1918<head>1919<title>The title</title>1920<link rel="stylesheet" href="blah.css" type="text/css" id="l1">1921</head>1922<body>1923<custom-dashed-tag class="dashed" id="dash1">Hello there.</custom-dashed-tag>1924<div id="main" class="fancy">1925<div id="inner">1926<h1 id="header1">An H1</h1>1927<p>Some text</p>1928<p class="onep" id="p1">Some more text</p>1929<h2 id="header2">An H2</h2>1930<p class="class1 class2 class3" id="pmulti">Another</p>1931<a href="http://bob.example.org/" rel="friend met" id="bob">Bob</a>1932<h2 id="header3">Another H2</h2>1933<a id="me" href="http://simonwillison.net/" rel="me">me</a>1934<span class="s1">1935<a href="#" id="s1a1">span1a1</a>1936<a href="#" id="s1a2">span1a2 <span id="s1a2s1">test</span></a>1937<span class="span2">1938<a href="#" id="s2a1">span2a1</a>1939</span>1940<span class="span3"></span>1941<custom-dashed-tag class="dashed" id="dash2"/>1942<div data-tag="dashedvalue" id="data1"/>1943</span>1944</div>1945<x id="xid">1946<z id="zida"/>1947<z id="zidab"/>1948<z id="zidac"/>1949</x>1950<y id="yid">1951<z id="zidb"/>1952</y>1953<p lang="en" id="lang-en">English</p>1954<p lang="en-gb" id="lang-en-gb">English UK</p>1955<p lang="en-us" id="lang-en-us">English US</p>1956<p lang="fr" id="lang-fr">French</p>1957</div>19581959<div id="footer">1960</div>1961"""19621963def setUp(self):1964self.soup = BeautifulSoup(self.HTML, 'html.parser')19651966def assertSelects(self, selector, expected_ids, **kwargs):1967el_ids = [el['id'] for el in self.soup.select(selector, **kwargs)]1968el_ids.sort()1969expected_ids.sort()1970self.assertEqual(expected_ids, el_ids,1971"Selector %s, expected [%s], got [%s]" % (1972selector, ', '.join(expected_ids), ', '.join(el_ids)1973)1974)19751976assertSelect = assertSelects19771978def assertSelectMultiple(self, *tests):1979for selector, expected_ids in tests:1980self.assertSelect(selector, expected_ids)19811982def test_one_tag_one(self):1983els = self.soup.select('title')1984self.assertEqual(len(els), 1)1985self.assertEqual(els[0].name, 'title')1986self.assertEqual(els[0].contents, ['The title'])19871988def test_one_tag_many(self):1989els = self.soup.select('div')1990self.assertEqual(len(els), 4)1991for div in els:1992self.assertEqual(div.name, 'div')19931994el = self.soup.select_one('div')1995self.assertEqual('main', el['id'])19961997def test_select_one_returns_none_if_no_match(self):1998match = self.soup.select_one('nonexistenttag')1999self.assertEqual(None, match)200020012002def test_tag_in_tag_one(self):2003els = self.soup.select('div div')2004self.assertSelects('div div', ['inner', 'data1'])20052006def test_tag_in_tag_many(self):2007for selector in ('html div', 'html body div', 'body div'):2008self.assertSelects(selector, ['data1', 'main', 'inner', 'footer'])200920102011def test_limit(self):2012self.assertSelects('html div', ['main'], limit=1)2013self.assertSelects('html body div', ['inner', 'main'], limit=2)2014self.assertSelects('body div', ['data1', 'main', 'inner', 'footer'],2015limit=10)20162017def test_tag_no_match(self):2018self.assertEqual(len(self.soup.select('del')), 0)20192020def test_invalid_tag(self):2021self.assertRaises(SelectorSyntaxError, self.soup.select, 'tag%t')20222023def test_select_dashed_tag_ids(self):2024self.assertSelects('custom-dashed-tag', ['dash1', 'dash2'])20252026def test_select_dashed_by_id(self):2027dashed = self.soup.select('custom-dashed-tag[id=\"dash2\"]')2028self.assertEqual(dashed[0].name, 'custom-dashed-tag')2029self.assertEqual(dashed[0]['id'], 'dash2')20302031def test_dashed_tag_text(self):2032self.assertEqual(self.soup.select('body > custom-dashed-tag')[0].text, 'Hello there.')20332034def test_select_dashed_matches_find_all(self):2035self.assertEqual(self.soup.select('custom-dashed-tag'), self.soup.find_all('custom-dashed-tag'))20362037def test_header_tags(self):2038self.assertSelectMultiple(2039('h1', ['header1']),2040('h2', ['header2', 'header3']),2041)20422043def test_class_one(self):2044for selector in ('.onep', 'p.onep', 'html p.onep'):2045els = self.soup.select(selector)2046self.assertEqual(len(els), 1)2047self.assertEqual(els[0].name, 'p')2048self.assertEqual(els[0]['class'], ['onep'])20492050def test_class_mismatched_tag(self):2051els = self.soup.select('div.onep')2052self.assertEqual(len(els), 0)20532054def test_one_id(self):2055for selector in ('div#inner', '#inner', 'div div#inner'):2056self.assertSelects(selector, ['inner'])20572058def test_bad_id(self):2059els = self.soup.select('#doesnotexist')2060self.assertEqual(len(els), 0)20612062def test_items_in_id(self):2063els = self.soup.select('div#inner p')2064self.assertEqual(len(els), 3)2065for el in els:2066self.assertEqual(el.name, 'p')2067self.assertEqual(els[1]['class'], ['onep'])2068self.assertFalse(els[0].has_attr('class'))20692070def test_a_bunch_of_emptys(self):2071for selector in ('div#main del', 'div#main div.oops', 'div div#main'):2072self.assertEqual(len(self.soup.select(selector)), 0)20732074def test_multi_class_support(self):2075for selector in ('.class1', 'p.class1', '.class2', 'p.class2',2076'.class3', 'p.class3', 'html p.class2', 'div#inner .class2'):2077self.assertSelects(selector, ['pmulti'])20782079def test_multi_class_selection(self):2080for selector in ('.class1.class3', '.class3.class2',2081'.class1.class2.class3'):2082self.assertSelects(selector, ['pmulti'])20832084def test_child_selector(self):2085self.assertSelects('.s1 > a', ['s1a1', 's1a2'])2086self.assertSelects('.s1 > a span', ['s1a2s1'])20872088def test_child_selector_id(self):2089self.assertSelects('.s1 > a#s1a2 span', ['s1a2s1'])20902091def test_attribute_equals(self):2092self.assertSelectMultiple(2093('p[class="onep"]', ['p1']),2094('p[id="p1"]', ['p1']),2095('[class="onep"]', ['p1']),2096('[id="p1"]', ['p1']),2097('link[rel="stylesheet"]', ['l1']),2098('link[type="text/css"]', ['l1']),2099('link[href="blah.css"]', ['l1']),2100('link[href="no-blah.css"]', []),2101('[rel="stylesheet"]', ['l1']),2102('[type="text/css"]', ['l1']),2103('[href="blah.css"]', ['l1']),2104('[href="no-blah.css"]', []),2105('p[href="no-blah.css"]', []),2106('[href="no-blah.css"]', []),2107)21082109def test_attribute_tilde(self):2110self.assertSelectMultiple(2111('p[class~="class1"]', ['pmulti']),2112('p[class~="class2"]', ['pmulti']),2113('p[class~="class3"]', ['pmulti']),2114('[class~="class1"]', ['pmulti']),2115('[class~="class2"]', ['pmulti']),2116('[class~="class3"]', ['pmulti']),2117('a[rel~="friend"]', ['bob']),2118('a[rel~="met"]', ['bob']),2119('[rel~="friend"]', ['bob']),2120('[rel~="met"]', ['bob']),2121)21222123def test_attribute_startswith(self):2124self.assertSelectMultiple(2125('[rel^="style"]', ['l1']),2126('link[rel^="style"]', ['l1']),2127('notlink[rel^="notstyle"]', []),2128('[rel^="notstyle"]', []),2129('link[rel^="notstyle"]', []),2130('link[href^="bla"]', ['l1']),2131('a[href^="http://"]', ['bob', 'me']),2132('[href^="http://"]', ['bob', 'me']),2133('[id^="p"]', ['pmulti', 'p1']),2134('[id^="m"]', ['me', 'main']),2135('div[id^="m"]', ['main']),2136('a[id^="m"]', ['me']),2137('div[data-tag^="dashed"]', ['data1'])2138)21392140def test_attribute_endswith(self):2141self.assertSelectMultiple(2142('[href$=".css"]', ['l1']),2143('link[href$=".css"]', ['l1']),2144('link[id$="1"]', ['l1']),2145('[id$="1"]', ['data1', 'l1', 'p1', 'header1', 's1a1', 's2a1', 's1a2s1', 'dash1']),2146('div[id$="1"]', ['data1']),2147('[id$="noending"]', []),2148)21492150def test_attribute_contains(self):2151self.assertSelectMultiple(2152# From test_attribute_startswith2153('[rel*="style"]', ['l1']),2154('link[rel*="style"]', ['l1']),2155('notlink[rel*="notstyle"]', []),2156('[rel*="notstyle"]', []),2157('link[rel*="notstyle"]', []),2158('link[href*="bla"]', ['l1']),2159('[href*="http://"]', ['bob', 'me']),2160('[id*="p"]', ['pmulti', 'p1']),2161('div[id*="m"]', ['main']),2162('a[id*="m"]', ['me']),2163# From test_attribute_endswith2164('[href*=".css"]', ['l1']),2165('link[href*=".css"]', ['l1']),2166('link[id*="1"]', ['l1']),2167('[id*="1"]', ['data1', 'l1', 'p1', 'header1', 's1a1', 's1a2', 's2a1', 's1a2s1', 'dash1']),2168('div[id*="1"]', ['data1']),2169('[id*="noending"]', []),2170# New for this test2171('[href*="."]', ['bob', 'me', 'l1']),2172('a[href*="."]', ['bob', 'me']),2173('link[href*="."]', ['l1']),2174('div[id*="n"]', ['main', 'inner']),2175('div[id*="nn"]', ['inner']),2176('div[data-tag*="edval"]', ['data1'])2177)21782179def test_attribute_exact_or_hypen(self):2180self.assertSelectMultiple(2181('p[lang|="en"]', ['lang-en', 'lang-en-gb', 'lang-en-us']),2182('[lang|="en"]', ['lang-en', 'lang-en-gb', 'lang-en-us']),2183('p[lang|="fr"]', ['lang-fr']),2184('p[lang|="gb"]', []),2185)21862187def test_attribute_exists(self):2188self.assertSelectMultiple(2189('[rel]', ['l1', 'bob', 'me']),2190('link[rel]', ['l1']),2191('a[rel]', ['bob', 'me']),2192('[lang]', ['lang-en', 'lang-en-gb', 'lang-en-us', 'lang-fr']),2193('p[class]', ['p1', 'pmulti']),2194('[blah]', []),2195('p[blah]', []),2196('div[data-tag]', ['data1'])2197)21982199def test_quoted_space_in_selector_name(self):2200html = """<div style="display: wrong">nope</div>2201<div style="display: right">yes</div>2202"""2203soup = BeautifulSoup(html, 'html.parser')2204[chosen] = soup.select('div[style="display: right"]')2205self.assertEqual("yes", chosen.string)22062207def test_unsupported_pseudoclass(self):2208self.assertRaises(2209NotImplementedError, self.soup.select, "a:no-such-pseudoclass")22102211self.assertRaises(2212SelectorSyntaxError, self.soup.select, "a:nth-of-type(a)")22132214def test_nth_of_type(self):2215# Try to select first paragraph2216els = self.soup.select('div#inner p:nth-of-type(1)')2217self.assertEqual(len(els), 1)2218self.assertEqual(els[0].string, 'Some text')22192220# Try to select third paragraph2221els = self.soup.select('div#inner p:nth-of-type(3)')2222self.assertEqual(len(els), 1)2223self.assertEqual(els[0].string, 'Another')22242225# Try to select (non-existent!) fourth paragraph2226els = self.soup.select('div#inner p:nth-of-type(4)')2227self.assertEqual(len(els), 0)22282229# Zero will select no tags.2230els = self.soup.select('div p:nth-of-type(0)')2231self.assertEqual(len(els), 0)22322233def test_nth_of_type_direct_descendant(self):2234els = self.soup.select('div#inner > p:nth-of-type(1)')2235self.assertEqual(len(els), 1)2236self.assertEqual(els[0].string, 'Some text')22372238def test_id_child_selector_nth_of_type(self):2239self.assertSelects('#inner > p:nth-of-type(2)', ['p1'])22402241def test_select_on_element(self):2242# Other tests operate on the tree; this operates on an element2243# within the tree.2244inner = self.soup.find("div", id="main")2245selected = inner.select("div")2246# The <div id="inner"> tag was selected. The <div id="footer">2247# tag was not.2248self.assertSelectsIDs(selected, ['inner', 'data1'])22492250def test_overspecified_child_id(self):2251self.assertSelects(".fancy #inner", ['inner'])2252self.assertSelects(".normal #inner", [])22532254def test_adjacent_sibling_selector(self):2255self.assertSelects('#p1 + h2', ['header2'])2256self.assertSelects('#p1 + h2 + p', ['pmulti'])2257self.assertSelects('#p1 + #header2 + .class1', ['pmulti'])2258self.assertEqual([], self.soup.select('#p1 + p'))22592260def test_general_sibling_selector(self):2261self.assertSelects('#p1 ~ h2', ['header2', 'header3'])2262self.assertSelects('#p1 ~ #header2', ['header2'])2263self.assertSelects('#p1 ~ h2 + a', ['me'])2264self.assertSelects('#p1 ~ h2 + [rel="me"]', ['me'])2265self.assertEqual([], self.soup.select('#inner ~ h2'))22662267def test_dangling_combinator(self):2268self.assertRaises(SelectorSyntaxError, self.soup.select, 'h1 >')22692270def test_sibling_combinator_wont_select_same_tag_twice(self):2271self.assertSelects('p[lang] ~ p', ['lang-en-gb', 'lang-en-us', 'lang-fr'])22722273# Test the selector grouping operator (the comma)2274def test_multiple_select(self):2275self.assertSelects('x, y', ['xid', 'yid'])22762277def test_multiple_select_with_no_space(self):2278self.assertSelects('x,y', ['xid', 'yid'])22792280def test_multiple_select_with_more_space(self):2281self.assertSelects('x, y', ['xid', 'yid'])22822283def test_multiple_select_duplicated(self):2284self.assertSelects('x, x', ['xid'])22852286def test_multiple_select_sibling(self):2287self.assertSelects('x, y ~ p[lang=fr]', ['xid', 'lang-fr'])22882289def test_multiple_select_tag_and_direct_descendant(self):2290self.assertSelects('x, y > z', ['xid', 'zidb'])22912292def test_multiple_select_direct_descendant_and_tags(self):2293self.assertSelects('div > x, y, z', ['xid', 'yid', 'zida', 'zidb', 'zidab', 'zidac'])22942295def test_multiple_select_indirect_descendant(self):2296self.assertSelects('div x,y, z', ['xid', 'yid', 'zida', 'zidb', 'zidab', 'zidac'])22972298def test_invalid_multiple_select(self):2299self.assertRaises(SelectorSyntaxError, self.soup.select, ',x, y')2300self.assertRaises(SelectorSyntaxError, self.soup.select, 'x,,y')23012302def test_multiple_select_attrs(self):2303self.assertSelects('p[lang=en], p[lang=en-gb]', ['lang-en', 'lang-en-gb'])23042305def test_multiple_select_ids(self):2306self.assertSelects('x, y > z[id=zida], z[id=zidab], z[id=zidb]', ['xid', 'zidb', 'zidab'])23072308def test_multiple_select_nested(self):2309self.assertSelects('body > div > x, y > z', ['xid', 'zidb'])23102311def test_select_duplicate_elements(self):2312# When markup contains duplicate elements, a multiple select2313# will find all of them.2314markup = '<div class="c1"/><div class="c2"/><div class="c1"/>'2315soup = BeautifulSoup(markup, 'html.parser')2316selected = soup.select(".c1, .c2")2317self.assertEqual(3, len(selected))23182319# Verify that find_all finds the same elements, though because2320# of an implementation detail it finds them in a different2321# order.2322for element in soup.find_all(class_=['c1', 'c2']):2323assert element in selected232423252326