test_tree.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  1. # -*- coding: utf-8 -*-
  2. """Tests for Beautiful Soup's tree traversal methods.
  3. The tree traversal methods are the main advantage of using Beautiful
  4. Soup over just using a parser.
  5. Different parsers will build different Beautiful Soup trees given the
  6. same markup, but all Beautiful Soup trees can be traversed with the
  7. methods tested here.
  8. """
  9. from pdb import set_trace
  10. import pytest
  11. import re
  12. import warnings
  13. from bs4 import BeautifulSoup
  14. from bs4.builder import (
  15. builder_registry,
  16. HTMLParserTreeBuilder,
  17. )
  18. from bs4.element import (
  19. CData,
  20. Comment,
  21. Declaration,
  22. Doctype,
  23. Formatter,
  24. NavigableString,
  25. Script,
  26. SoupStrainer,
  27. Stylesheet,
  28. Tag,
  29. TemplateString,
  30. )
  31. from . import (
  32. SoupTest,
  33. skipIf,
  34. )
  35. class TestFind(SoupTest):
  36. """Basic tests of the find() method.
  37. find() just calls find_all() with limit=1, so it's not tested all
  38. that thouroughly here.
  39. """
  40. def test_find_tag(self):
  41. soup = self.soup("<a>1</a><b>2</b><a>3</a><b>4</b>")
  42. assert soup.find("b").string == "2"
  43. def test_unicode_text_find(self):
  44. soup = self.soup('<h1>Räksmörgås</h1>')
  45. assert soup.find(string='Räksmörgås') == 'Räksmörgås'
  46. def test_unicode_attribute_find(self):
  47. soup = self.soup('<h1 id="Räksmörgås">here it is</h1>')
  48. str(soup)
  49. assert "here it is" == soup.find(id='Räksmörgås').text
  50. def test_find_everything(self):
  51. """Test an optimization that finds all tags."""
  52. soup = self.soup("<a>foo</a><b>bar</b>")
  53. assert 2 == len(soup.find_all())
  54. def test_find_everything_with_name(self):
  55. """Test an optimization that finds all tags with a given name."""
  56. soup = self.soup("<a>foo</a><b>bar</b><a>baz</a>")
  57. assert 2 == len(soup.find_all('a'))
  58. class TestFindAll(SoupTest):
  59. """Basic tests of the find_all() method."""
  60. def test_find_all_text_nodes(self):
  61. """You can search the tree for text nodes."""
  62. soup = self.soup("<html>Foo<b>bar</b>\xbb</html>")
  63. # Exact match.
  64. assert soup.find_all(string="bar") == ["bar"]
  65. # Match any of a number of strings.
  66. assert soup.find_all(string=["Foo", "bar"]) == ["Foo", "bar"]
  67. # Match a regular expression.
  68. assert soup.find_all(string=re.compile('.*')) == ["Foo", "bar", '\xbb']
  69. # Match anything.
  70. assert soup.find_all(string=True) == ["Foo", "bar", '\xbb']
  71. def test_find_all_limit(self):
  72. """You can limit the number of items returned by find_all."""
  73. soup = self.soup("<a>1</a><a>2</a><a>3</a><a>4</a><a>5</a>")
  74. self.assert_selects(soup.find_all('a', limit=3), ["1", "2", "3"])
  75. self.assert_selects(soup.find_all('a', limit=1), ["1"])
  76. self.assert_selects(
  77. soup.find_all('a', limit=10), ["1", "2", "3", "4", "5"])
  78. # A limit of 0 means no limit.
  79. self.assert_selects(
  80. soup.find_all('a', limit=0), ["1", "2", "3", "4", "5"])
  81. def test_calling_a_tag_is_calling_findall(self):
  82. soup = self.soup("<a>1</a><b>2<a id='foo'>3</a></b>")
  83. self.assert_selects(soup('a', limit=1), ["1"])
  84. self.assert_selects(soup.b(id="foo"), ["3"])
  85. def test_find_all_with_self_referential_data_structure_does_not_cause_infinite_recursion(self):
  86. soup = self.soup("<a></a>")
  87. # Create a self-referential list.
  88. l = []
  89. l.append(l)
  90. # Without special code in _normalize_search_value, this would cause infinite
  91. # recursion.
  92. assert [] == soup.find_all(l)
  93. def test_find_all_resultset(self):
  94. """All find_all calls return a ResultSet"""
  95. soup = self.soup("<a></a>")
  96. result = soup.find_all("a")
  97. assert hasattr(result, "source")
  98. result = soup.find_all(True)
  99. assert hasattr(result, "source")
  100. result = soup.find_all(string="foo")
  101. assert hasattr(result, "source")
  102. class TestFindAllBasicNamespaces(SoupTest):
  103. def test_find_by_namespaced_name(self):
  104. soup = self.soup('<mathml:msqrt>4</mathml:msqrt><a svg:fill="red">')
  105. assert "4" == soup.find("mathml:msqrt").string
  106. assert "a" == soup.find(attrs= { "svg:fill" : "red" }).name
  107. class TestFindAllByName(SoupTest):
  108. """Test ways of finding tags by tag name."""
  109. def setup_method(self):
  110. self.tree = self.soup("""<a>First tag.</a>
  111. <b>Second tag.</b>
  112. <c>Third <a>Nested tag.</a> tag.</c>""")
  113. def test_find_all_by_tag_name(self):
  114. # Find all the <a> tags.
  115. self.assert_selects(
  116. self.tree.find_all('a'), ['First tag.', 'Nested tag.'])
  117. def test_find_all_by_name_and_text(self):
  118. self.assert_selects(
  119. self.tree.find_all('a', string='First tag.'), ['First tag.'])
  120. self.assert_selects(
  121. self.tree.find_all('a', string=True), ['First tag.', 'Nested tag.'])
  122. self.assert_selects(
  123. self.tree.find_all('a', string=re.compile("tag")),
  124. ['First tag.', 'Nested tag.'])
  125. def test_find_all_on_non_root_element(self):
  126. # You can call find_all on any node, not just the root.
  127. self.assert_selects(self.tree.c.find_all('a'), ['Nested tag.'])
  128. def test_calling_element_invokes_find_all(self):
  129. self.assert_selects(self.tree('a'), ['First tag.', 'Nested tag.'])
  130. def test_find_all_by_tag_strainer(self):
  131. self.assert_selects(
  132. self.tree.find_all(SoupStrainer('a')),
  133. ['First tag.', 'Nested tag.'])
  134. def test_find_all_by_tag_names(self):
  135. self.assert_selects(
  136. self.tree.find_all(['a', 'b']),
  137. ['First tag.', 'Second tag.', 'Nested tag.'])
  138. def test_find_all_by_tag_dict(self):
  139. self.assert_selects(
  140. self.tree.find_all({'a' : True, 'b' : True}),
  141. ['First tag.', 'Second tag.', 'Nested tag.'])
  142. def test_find_all_by_tag_re(self):
  143. self.assert_selects(
  144. self.tree.find_all(re.compile('^[ab]$')),
  145. ['First tag.', 'Second tag.', 'Nested tag.'])
  146. def test_find_all_with_tags_matching_method(self):
  147. # You can define an oracle method that determines whether
  148. # a tag matches the search.
  149. def id_matches_name(tag):
  150. return tag.name == tag.get('id')
  151. tree = self.soup("""<a id="a">Match 1.</a>
  152. <a id="1">Does not match.</a>
  153. <b id="b">Match 2.</a>""")
  154. self.assert_selects(
  155. tree.find_all(id_matches_name), ["Match 1.", "Match 2."])
  156. def test_find_with_multi_valued_attribute(self):
  157. soup = self.soup(
  158. "<div class='a b'>1</div><div class='a c'>2</div><div class='a d'>3</div>"
  159. )
  160. r1 = soup.find('div', 'a d');
  161. r2 = soup.find('div', re.compile(r'a d'));
  162. r3, r4 = soup.find_all('div', ['a b', 'a d']);
  163. assert '3' == r1.string
  164. assert '3' == r2.string
  165. assert '1' == r3.string
  166. assert '3' == r4.string
  167. class TestFindAllByAttribute(SoupTest):
  168. def test_find_all_by_attribute_name(self):
  169. # You can pass in keyword arguments to find_all to search by
  170. # attribute.
  171. tree = self.soup("""
  172. <a id="first">Matching a.</a>
  173. <a id="second">
  174. Non-matching <b id="first">Matching b.</b>a.
  175. </a>""")
  176. self.assert_selects(tree.find_all(id='first'),
  177. ["Matching a.", "Matching b."])
  178. def test_find_all_by_utf8_attribute_value(self):
  179. peace = "םולש".encode("utf8")
  180. data = '<a title="םולש"></a>'.encode("utf8")
  181. soup = self.soup(data)
  182. assert [soup.a] == soup.find_all(title=peace)
  183. assert [soup.a] == soup.find_all(title=peace.decode("utf8"))
  184. assert [soup.a], soup.find_all(title=[peace, "something else"])
  185. def test_find_all_by_attribute_dict(self):
  186. # You can pass in a dictionary as the argument 'attrs'. This
  187. # lets you search for attributes like 'name' (a fixed argument
  188. # to find_all) and 'class' (a reserved word in Python.)
  189. tree = self.soup("""
  190. <a name="name1" class="class1">Name match.</a>
  191. <a name="name2" class="class2">Class match.</a>
  192. <a name="name3" class="class3">Non-match.</a>
  193. <name1>A tag called 'name1'.</name1>
  194. """)
  195. # This doesn't do what you want.
  196. self.assert_selects(tree.find_all(name='name1'),
  197. ["A tag called 'name1'."])
  198. # This does what you want.
  199. self.assert_selects(tree.find_all(attrs={'name' : 'name1'}),
  200. ["Name match."])
  201. self.assert_selects(tree.find_all(attrs={'class' : 'class2'}),
  202. ["Class match."])
  203. def test_find_all_by_class(self):
  204. tree = self.soup("""
  205. <a class="1">Class 1.</a>
  206. <a class="2">Class 2.</a>
  207. <b class="1">Class 1.</b>
  208. <c class="3 4">Class 3 and 4.</c>
  209. """)
  210. # Passing in the class_ keyword argument will search against
  211. # the 'class' attribute.
  212. self.assert_selects(tree.find_all('a', class_='1'), ['Class 1.'])
  213. self.assert_selects(tree.find_all('c', class_='3'), ['Class 3 and 4.'])
  214. self.assert_selects(tree.find_all('c', class_='4'), ['Class 3 and 4.'])
  215. # Passing in a string to 'attrs' will also search the CSS class.
  216. self.assert_selects(tree.find_all('a', '1'), ['Class 1.'])
  217. self.assert_selects(tree.find_all(attrs='1'), ['Class 1.', 'Class 1.'])
  218. self.assert_selects(tree.find_all('c', '3'), ['Class 3 and 4.'])
  219. self.assert_selects(tree.find_all('c', '4'), ['Class 3 and 4.'])
  220. def test_find_by_class_when_multiple_classes_present(self):
  221. tree = self.soup("<gar class='foo bar'>Found it</gar>")
  222. f = tree.find_all("gar", class_=re.compile("o"))
  223. self.assert_selects(f, ["Found it"])
  224. f = tree.find_all("gar", class_=re.compile("a"))
  225. self.assert_selects(f, ["Found it"])
  226. # If the search fails to match the individual strings "foo" and "bar",
  227. # it will be tried against the combined string "foo bar".
  228. f = tree.find_all("gar", class_=re.compile("o b"))
  229. self.assert_selects(f, ["Found it"])
  230. def test_find_all_with_non_dictionary_for_attrs_finds_by_class(self):
  231. soup = self.soup("<a class='bar'>Found it</a>")
  232. self.assert_selects(soup.find_all("a", re.compile("ba")), ["Found it"])
  233. def big_attribute_value(value):
  234. return len(value) > 3
  235. self.assert_selects(soup.find_all("a", big_attribute_value), [])
  236. def small_attribute_value(value):
  237. return len(value) <= 3
  238. self.assert_selects(
  239. soup.find_all("a", small_attribute_value), ["Found it"])
  240. def test_find_all_with_string_for_attrs_finds_multiple_classes(self):
  241. soup = self.soup('<a class="foo bar"></a><a class="foo"></a>')
  242. a, a2 = soup.find_all("a")
  243. assert [a, a2], soup.find_all("a", "foo")
  244. assert [a], soup.find_all("a", "bar")
  245. # If you specify the class as a string that contains a
  246. # space, only that specific value will be found.
  247. assert [a] == soup.find_all("a", class_="foo bar")
  248. assert [a] == soup.find_all("a", "foo bar")
  249. assert [] == soup.find_all("a", "bar foo")
  250. def test_find_all_by_attribute_soupstrainer(self):
  251. tree = self.soup("""
  252. <a id="first">Match.</a>
  253. <a id="second">Non-match.</a>""")
  254. strainer = SoupStrainer(attrs={'id' : 'first'})
  255. self.assert_selects(tree.find_all(strainer), ['Match.'])
  256. def test_find_all_with_missing_attribute(self):
  257. # You can pass in None as the value of an attribute to find_all.
  258. # This will match tags that do not have that attribute set.
  259. tree = self.soup("""<a id="1">ID present.</a>
  260. <a>No ID present.</a>
  261. <a id="">ID is empty.</a>""")
  262. self.assert_selects(tree.find_all('a', id=None), ["No ID present."])
  263. def test_find_all_with_defined_attribute(self):
  264. # You can pass in None as the value of an attribute to find_all.
  265. # This will match tags that have that attribute set to any value.
  266. tree = self.soup("""<a id="1">ID present.</a>
  267. <a>No ID present.</a>
  268. <a id="">ID is empty.</a>""")
  269. self.assert_selects(
  270. tree.find_all(id=True), ["ID present.", "ID is empty."])
  271. def test_find_all_with_numeric_attribute(self):
  272. # If you search for a number, it's treated as a string.
  273. tree = self.soup("""<a id=1>Unquoted attribute.</a>
  274. <a id="1">Quoted attribute.</a>""")
  275. expected = ["Unquoted attribute.", "Quoted attribute."]
  276. self.assert_selects(tree.find_all(id=1), expected)
  277. self.assert_selects(tree.find_all(id="1"), expected)
  278. def test_find_all_with_list_attribute_values(self):
  279. # You can pass a list of attribute values instead of just one,
  280. # and you'll get tags that match any of the values.
  281. tree = self.soup("""<a id="1">1</a>
  282. <a id="2">2</a>
  283. <a id="3">3</a>
  284. <a>No ID.</a>""")
  285. self.assert_selects(tree.find_all(id=["1", "3", "4"]),
  286. ["1", "3"])
  287. def test_find_all_with_regular_expression_attribute_value(self):
  288. # You can pass a regular expression as an attribute value, and
  289. # you'll get tags whose values for that attribute match the
  290. # regular expression.
  291. tree = self.soup("""<a id="a">One a.</a>
  292. <a id="aa">Two as.</a>
  293. <a id="ab">Mixed as and bs.</a>
  294. <a id="b">One b.</a>
  295. <a>No ID.</a>""")
  296. self.assert_selects(tree.find_all(id=re.compile("^a+$")),
  297. ["One a.", "Two as."])
  298. def test_find_by_name_and_containing_string(self):
  299. soup = self.soup("<b>foo</b><b>bar</b><a>foo</a>")
  300. a = soup.a
  301. assert [a] == soup.find_all("a", string="foo")
  302. assert [] == soup.find_all("a", string="bar")
  303. def test_find_by_name_and_containing_string_when_string_is_buried(self):
  304. soup = self.soup("<a>foo</a><a><b><c>foo</c></b></a>")
  305. assert soup.find_all("a") == soup.find_all("a", string="foo")
  306. def test_find_by_attribute_and_containing_string(self):
  307. soup = self.soup('<b id="1">foo</b><a id="2">foo</a>')
  308. a = soup.a
  309. assert [a] == soup.find_all(id=2, string="foo")
  310. assert [] == soup.find_all(id=1, string="bar")
  311. class TestSmooth(SoupTest):
  312. """Test Tag.smooth."""
  313. def test_smooth(self):
  314. soup = self.soup("<div>a</div>")
  315. div = soup.div
  316. div.append("b")
  317. div.append("c")
  318. div.append(Comment("Comment 1"))
  319. div.append(Comment("Comment 2"))
  320. div.append("d")
  321. builder = self.default_builder()
  322. span = Tag(soup, builder, 'span')
  323. span.append('1')
  324. span.append('2')
  325. div.append(span)
  326. # At this point the tree has a bunch of adjacent
  327. # NavigableStrings. This is normal, but it has no meaning in
  328. # terms of HTML, so we may want to smooth things out for
  329. # output.
  330. # Since the <span> tag has two children, its .string is None.
  331. assert None == div.span.string
  332. assert 7 == len(div.contents)
  333. div.smooth()
  334. assert 5 == len(div.contents)
  335. # The three strings at the beginning of div.contents have been
  336. # merged into on string.
  337. #
  338. assert 'abc' == div.contents[0]
  339. # The call is recursive -- the <span> tag was also smoothed.
  340. assert '12' == div.span.string
  341. # The two comments have _not_ been merged, even though
  342. # comments are strings. Merging comments would change the
  343. # meaning of the HTML.
  344. assert 'Comment 1' == div.contents[1]
  345. assert 'Comment 2' == div.contents[2]
  346. class TestIndex(SoupTest):
  347. """Test Tag.index"""
  348. def test_index(self):
  349. tree = self.soup("""<div>
  350. <a>Identical</a>
  351. <b>Not identical</b>
  352. <a>Identical</a>
  353. <c><d>Identical with child</d></c>
  354. <b>Also not identical</b>
  355. <c><d>Identical with child</d></c>
  356. </div>""")
  357. div = tree.div
  358. for i, element in enumerate(div.contents):
  359. assert i == div.index(element)
  360. with pytest.raises(ValueError):
  361. tree.index(1)
  362. class TestParentOperations(SoupTest):
  363. """Test navigation and searching through an element's parents."""
  364. def setup_method(self):
  365. self.tree = self.soup('''<ul id="empty"></ul>
  366. <ul id="top">
  367. <ul id="middle">
  368. <ul id="bottom">
  369. <b>Start here</b>
  370. </ul>
  371. </ul>''')
  372. self.start = self.tree.b
  373. def test_parent(self):
  374. assert self.start.parent['id'] == 'bottom'
  375. assert self.start.parent.parent['id'] == 'middle'
  376. assert self.start.parent.parent.parent['id'] == 'top'
  377. def test_parent_of_top_tag_is_soup_object(self):
  378. top_tag = self.tree.contents[0]
  379. assert top_tag.parent == self.tree
  380. def test_soup_object_has_no_parent(self):
  381. assert None == self.tree.parent
  382. def test_find_parents(self):
  383. self.assert_selects_ids(
  384. self.start.find_parents('ul'), ['bottom', 'middle', 'top'])
  385. self.assert_selects_ids(
  386. self.start.find_parents('ul', id="middle"), ['middle'])
  387. def test_find_parent(self):
  388. assert self.start.find_parent('ul')['id'] == 'bottom'
  389. assert self.start.find_parent('ul', id='top')['id'] == 'top'
  390. def test_parent_of_text_element(self):
  391. text = self.tree.find(string="Start here")
  392. assert text.parent.name == 'b'
  393. def test_text_element_find_parent(self):
  394. text = self.tree.find(string="Start here")
  395. assert text.find_parent('ul')['id'] == 'bottom'
  396. def test_parent_generator(self):
  397. parents = [parent['id'] for parent in self.start.parents
  398. if parent is not None and 'id' in parent.attrs]
  399. assert parents, ['bottom', 'middle' == 'top']
  400. class ProximityTest(SoupTest):
  401. def setup_method(self):
  402. self.tree = self.soup(
  403. '<html id="start"><head></head><body><b id="1">One</b><b id="2">Two</b><b id="3">Three</b></body></html>')
  404. class TestNextOperations(ProximityTest):
  405. def setup_method(self):
  406. super(TestNextOperations, self).setup_method()
  407. self.start = self.tree.b
  408. def test_next(self):
  409. assert self.start.next_element == "One"
  410. assert self.start.next_element.next_element['id'] == "2"
  411. def test_next_of_last_item_is_none(self):
  412. last = self.tree.find(string="Three")
  413. assert last.next_element == None
  414. def test_next_of_root_is_none(self):
  415. # The document root is outside the next/previous chain.
  416. assert self.tree.next_element == None
  417. def test_find_all_next(self):
  418. self.assert_selects(self.start.find_all_next('b'), ["Two", "Three"])
  419. self.start.find_all_next(id=3)
  420. self.assert_selects(self.start.find_all_next(id=3), ["Three"])
  421. def test_find_next(self):
  422. assert self.start.find_next('b')['id'] == '2'
  423. assert self.start.find_next(string="Three") == "Three"
  424. def test_find_next_for_text_element(self):
  425. text = self.tree.find(string="One")
  426. assert text.find_next("b").string == "Two"
  427. self.assert_selects(text.find_all_next("b"), ["Two", "Three"])
  428. def test_next_generator(self):
  429. start = self.tree.find(string="Two")
  430. successors = [node for node in start.next_elements]
  431. # There are two successors: the final <b> tag and its text contents.
  432. tag, contents = successors
  433. assert tag['id'] == '3'
  434. assert contents == "Three"
  435. class TestPreviousOperations(ProximityTest):
  436. def setup_method(self):
  437. super(TestPreviousOperations, self).setup_method()
  438. self.end = self.tree.find(string="Three")
  439. def test_previous(self):
  440. assert self.end.previous_element['id'] == "3"
  441. assert self.end.previous_element.previous_element == "Two"
  442. def test_previous_of_first_item_is_none(self):
  443. first = self.tree.find('html')
  444. assert first.previous_element == None
  445. def test_previous_of_root_is_none(self):
  446. # The document root is outside the next/previous chain.
  447. assert self.tree.previous_element == None
  448. def test_find_all_previous(self):
  449. # The <b> tag containing the "Three" node is the predecessor
  450. # of the "Three" node itself, which is why "Three" shows up
  451. # here.
  452. self.assert_selects(
  453. self.end.find_all_previous('b'), ["Three", "Two", "One"])
  454. self.assert_selects(self.end.find_all_previous(id=1), ["One"])
  455. def test_find_previous(self):
  456. assert self.end.find_previous('b')['id'] == '3'
  457. assert self.end.find_previous(string="One") == "One"
  458. def test_find_previous_for_text_element(self):
  459. text = self.tree.find(string="Three")
  460. assert text.find_previous("b").string == "Three"
  461. self.assert_selects(
  462. text.find_all_previous("b"), ["Three", "Two", "One"])
  463. def test_previous_generator(self):
  464. start = self.tree.find(string="One")
  465. predecessors = [node for node in start.previous_elements]
  466. # There are four predecessors: the <b> tag containing "One"
  467. # the <body> tag, the <head> tag, and the <html> tag.
  468. b, body, head, html = predecessors
  469. assert b['id'] == '1'
  470. assert body.name == "body"
  471. assert head.name == "head"
  472. assert html.name == "html"
  473. class SiblingTest(SoupTest):
  474. def setup_method(self):
  475. markup = '''<html>
  476. <span id="1">
  477. <span id="1.1"></span>
  478. </span>
  479. <span id="2">
  480. <span id="2.1"></span>
  481. </span>
  482. <span id="3">
  483. <span id="3.1"></span>
  484. </span>
  485. <span id="4"></span>
  486. </html>'''
  487. # All that whitespace looks good but makes the tests more
  488. # difficult. Get rid of it.
  489. markup = re.compile(r"\n\s*").sub("", markup)
  490. self.tree = self.soup(markup)
  491. class TestNextSibling(SiblingTest):
  492. def setup_method(self):
  493. super(TestNextSibling, self).setup_method()
  494. self.start = self.tree.find(id="1")
  495. def test_next_sibling_of_root_is_none(self):
  496. assert self.tree.next_sibling == None
  497. def test_next_sibling(self):
  498. assert self.start.next_sibling['id'] == '2'
  499. assert self.start.next_sibling.next_sibling['id'] == '3'
  500. # Note the difference between next_sibling and next_element.
  501. assert self.start.next_element['id'] == '1.1'
  502. def test_next_sibling_may_not_exist(self):
  503. assert self.tree.html.next_sibling == None
  504. nested_span = self.tree.find(id="1.1")
  505. assert nested_span.next_sibling == None
  506. last_span = self.tree.find(id="4")
  507. assert last_span.next_sibling == None
  508. def test_find_next_sibling(self):
  509. assert self.start.find_next_sibling('span')['id'] == '2'
  510. def test_next_siblings(self):
  511. self.assert_selects_ids(self.start.find_next_siblings("span"),
  512. ['2', '3', '4'])
  513. self.assert_selects_ids(self.start.find_next_siblings(id='3'), ['3'])
  514. def test_next_sibling_for_text_element(self):
  515. soup = self.soup("Foo<b>bar</b>baz")
  516. start = soup.find(string="Foo")
  517. assert start.next_sibling.name == 'b'
  518. assert start.next_sibling.next_sibling == 'baz'
  519. self.assert_selects(start.find_next_siblings('b'), ['bar'])
  520. assert start.find_next_sibling(string="baz") == "baz"
  521. assert start.find_next_sibling(string="nonesuch") == None
  522. class TestPreviousSibling(SiblingTest):
  523. def setup_method(self):
  524. super(TestPreviousSibling, self).setup_method()
  525. self.end = self.tree.find(id="4")
  526. def test_previous_sibling_of_root_is_none(self):
  527. assert self.tree.previous_sibling == None
  528. def test_previous_sibling(self):
  529. assert self.end.previous_sibling['id'] == '3'
  530. assert self.end.previous_sibling.previous_sibling['id'] == '2'
  531. # Note the difference between previous_sibling and previous_element.
  532. assert self.end.previous_element['id'] == '3.1'
  533. def test_previous_sibling_may_not_exist(self):
  534. assert self.tree.html.previous_sibling == None
  535. nested_span = self.tree.find(id="1.1")
  536. assert nested_span.previous_sibling == None
  537. first_span = self.tree.find(id="1")
  538. assert first_span.previous_sibling == None
  539. def test_find_previous_sibling(self):
  540. assert self.end.find_previous_sibling('span')['id'] == '3'
  541. def test_previous_siblings(self):
  542. self.assert_selects_ids(self.end.find_previous_siblings("span"),
  543. ['3', '2', '1'])
  544. self.assert_selects_ids(self.end.find_previous_siblings(id='1'), ['1'])
  545. def test_previous_sibling_for_text_element(self):
  546. soup = self.soup("Foo<b>bar</b>baz")
  547. start = soup.find(string="baz")
  548. assert start.previous_sibling.name == 'b'
  549. assert start.previous_sibling.previous_sibling == 'Foo'
  550. self.assert_selects(start.find_previous_siblings('b'), ['bar'])
  551. assert start.find_previous_sibling(string="Foo") == "Foo"
  552. assert start.find_previous_sibling(string="nonesuch") == None
  553. class TestTreeModification(SoupTest):
  554. def test_attribute_modification(self):
  555. soup = self.soup('<a id="1"></a>')
  556. soup.a['id'] = 2
  557. assert soup.decode() == self.document_for('<a id="2"></a>')
  558. del(soup.a['id'])
  559. assert soup.decode() == self.document_for('<a></a>')
  560. soup.a['id2'] = 'foo'
  561. assert soup.decode() == self.document_for('<a id2="foo"></a>')
  562. def test_new_tag_creation(self):
  563. builder = builder_registry.lookup('html')()
  564. soup = self.soup("<body></body>", builder=builder)
  565. a = Tag(soup, builder, 'a')
  566. ol = Tag(soup, builder, 'ol')
  567. a['href'] = 'http://foo.com/'
  568. soup.body.insert(0, a)
  569. soup.body.insert(1, ol)
  570. assert soup.body.encode() == b'<body><a href="http://foo.com/"></a><ol></ol></body>'
  571. def test_append_to_contents_moves_tag(self):
  572. doc = """<p id="1">Don't leave me <b>here</b>.</p>
  573. <p id="2">Don\'t leave!</p>"""
  574. soup = self.soup(doc)
  575. second_para = soup.find(id='2')
  576. bold = soup.b
  577. # Move the <b> tag to the end of the second paragraph.
  578. soup.find(id='2').append(soup.b)
  579. # The <b> tag is now a child of the second paragraph.
  580. assert bold.parent == second_para
  581. assert soup.decode() == self.document_for(
  582. '<p id="1">Don\'t leave me .</p>\n'
  583. '<p id="2">Don\'t leave!<b>here</b></p>'
  584. )
  585. def test_replace_with_returns_thing_that_was_replaced(self):
  586. text = "<a></a><b><c></c></b>"
  587. soup = self.soup(text)
  588. a = soup.a
  589. new_a = a.replace_with(soup.c)
  590. assert a == new_a
  591. def test_unwrap_returns_thing_that_was_replaced(self):
  592. text = "<a><b></b><c></c></a>"
  593. soup = self.soup(text)
  594. a = soup.a
  595. new_a = a.unwrap()
  596. assert a == new_a
  597. def test_replace_with_and_unwrap_give_useful_exception_when_tag_has_no_parent(self):
  598. soup = self.soup("<a><b>Foo</b></a><c>Bar</c>")
  599. a = soup.a
  600. a.extract()
  601. assert None == a.parent
  602. with pytest.raises(ValueError):
  603. a.unwrap()
  604. with pytest.raises(ValueError):
  605. a.replace_with(soup.c)
  606. def test_replace_tag_with_itself(self):
  607. text = "<a><b></b><c>Foo<d></d></c></a><a><e></e></a>"
  608. soup = self.soup(text)
  609. c = soup.c
  610. soup.c.replace_with(c)
  611. assert soup.decode() == self.document_for(text)
  612. def test_replace_tag_with_its_parent_raises_exception(self):
  613. text = "<a><b></b></a>"
  614. soup = self.soup(text)
  615. with pytest.raises(ValueError):
  616. soup.b.replace_with(soup.a)
  617. def test_insert_tag_into_itself_raises_exception(self):
  618. text = "<a><b></b></a>"
  619. soup = self.soup(text)
  620. with pytest.raises(ValueError):
  621. soup.a.insert(0, soup.a)
  622. def test_insert_beautifulsoup_object_inserts_children(self):
  623. """Inserting one BeautifulSoup object into another actually inserts all
  624. of its children -- you'll never combine BeautifulSoup objects.
  625. """
  626. soup = self.soup("<p>And now, a word:</p><p>And we're back.</p>")
  627. text = "<p>p2</p><p>p3</p>"
  628. to_insert = self.soup(text)
  629. soup.insert(1, to_insert)
  630. for i in soup.descendants:
  631. assert not isinstance(i, BeautifulSoup)
  632. p1, p2, p3, p4 = list(soup.children)
  633. assert "And now, a word:" == p1.string
  634. assert "p2" == p2.string
  635. assert "p3" == p3.string
  636. assert "And we're back." == p4.string
  637. def test_replace_with_maintains_next_element_throughout(self):
  638. soup = self.soup('<p><a>one</a><b>three</b></p>')
  639. a = soup.a
  640. b = a.contents[0]
  641. # Make it so the <a> tag has two text children.
  642. a.insert(1, "two")
  643. # Now replace each one with the empty string.
  644. left, right = a.contents
  645. left.replaceWith('')
  646. right.replaceWith('')
  647. # The <b> tag is still connected to the tree.
  648. assert "three" == soup.b.string
  649. def test_replace_final_node(self):
  650. soup = self.soup("<b>Argh!</b>")
  651. soup.find(string="Argh!").replace_with("Hooray!")
  652. new_text = soup.find(string="Hooray!")
  653. b = soup.b
  654. assert new_text.previous_element == b
  655. assert new_text.parent == b
  656. assert new_text.previous_element.next_element == new_text
  657. assert new_text.next_element == None
  658. def test_consecutive_text_nodes(self):
  659. # A builder should never create two consecutive text nodes,
  660. # but if you insert one next to another, Beautiful Soup will
  661. # handle it correctly.
  662. soup = self.soup("<a><b>Argh!</b><c></c></a>")
  663. soup.b.insert(1, "Hooray!")
  664. assert soup.decode() == self.document_for(
  665. "<a><b>Argh!Hooray!</b><c></c></a>"
  666. )
  667. new_text = soup.find(string="Hooray!")
  668. assert new_text.previous_element == "Argh!"
  669. assert new_text.previous_element.next_element == new_text
  670. assert new_text.previous_sibling == "Argh!"
  671. assert new_text.previous_sibling.next_sibling == new_text
  672. assert new_text.next_sibling == None
  673. assert new_text.next_element == soup.c
  674. def test_insert_string(self):
  675. soup = self.soup("<a></a>")
  676. soup.a.insert(0, "bar")
  677. soup.a.insert(0, "foo")
  678. # The string were added to the tag.
  679. assert ["foo", "bar"] == soup.a.contents
  680. # And they were converted to NavigableStrings.
  681. assert soup.a.contents[0].next_element == "bar"
  682. def test_insert_tag(self):
  683. builder = self.default_builder()
  684. soup = self.soup(
  685. "<a><b>Find</b><c>lady!</c><d></d></a>", builder=builder)
  686. magic_tag = Tag(soup, builder, 'magictag')
  687. magic_tag.insert(0, "the")
  688. soup.a.insert(1, magic_tag)
  689. assert soup.decode() == self.document_for(
  690. "<a><b>Find</b><magictag>the</magictag><c>lady!</c><d></d></a>"
  691. )
  692. # Make sure all the relationships are hooked up correctly.
  693. b_tag = soup.b
  694. assert b_tag.next_sibling == magic_tag
  695. assert magic_tag.previous_sibling == b_tag
  696. find = b_tag.find(string="Find")
  697. assert find.next_element == magic_tag
  698. assert magic_tag.previous_element == find
  699. c_tag = soup.c
  700. assert magic_tag.next_sibling == c_tag
  701. assert c_tag.previous_sibling == magic_tag
  702. the = magic_tag.find(string="the")
  703. assert the.parent == magic_tag
  704. assert the.next_element == c_tag
  705. assert c_tag.previous_element == the
  706. def test_append_child_thats_already_at_the_end(self):
  707. data = "<a><b></b></a>"
  708. soup = self.soup(data)
  709. soup.a.append(soup.b)
  710. assert data == soup.decode()
  711. def test_extend(self):
  712. data = "<a><b><c><d><e><f><g></g></f></e></d></c></b></a>"
  713. soup = self.soup(data)
  714. l = [soup.g, soup.f, soup.e, soup.d, soup.c, soup.b]
  715. soup.a.extend(l)
  716. assert "<a><g></g><f></f><e></e><d></d><c></c><b></b></a>" == soup.decode()
  717. def test_extend_with_another_tags_contents(self):
  718. data = '<body><div id="d1"><a>1</a><a>2</a><a>3</a><a>4</a></div><div id="d2"></div></body>'
  719. soup = self.soup(data)
  720. d1 = soup.find('div', id='d1')
  721. d2 = soup.find('div', id='d2')
  722. d2.extend(d1)
  723. assert '<div id="d1"></div>' == d1.decode()
  724. assert '<div id="d2"><a>1</a><a>2</a><a>3</a><a>4</a></div>' == d2.decode()
  725. def test_move_tag_to_beginning_of_parent(self):
  726. data = "<a><b></b><c></c><d></d></a>"
  727. soup = self.soup(data)
  728. soup.a.insert(0, soup.d)
  729. assert "<a><d></d><b></b><c></c></a>" == soup.decode()
  730. def test_insert_works_on_empty_element_tag(self):
  731. # This is a little strange, since most HTML parsers don't allow
  732. # markup like this to come through. But in general, we don't
  733. # know what the parser would or wouldn't have allowed, so
  734. # I'm letting this succeed for now.
  735. soup = self.soup("<br/>")
  736. soup.br.insert(1, "Contents")
  737. assert str(soup.br) == "<br>Contents</br>"
  738. def test_insert_before(self):
  739. soup = self.soup("<a>foo</a><b>bar</b>")
  740. soup.b.insert_before("BAZ")
  741. soup.a.insert_before("QUUX")
  742. assert soup.decode() == self.document_for(
  743. "QUUX<a>foo</a>BAZ<b>bar</b>"
  744. )
  745. soup.a.insert_before(soup.b)
  746. assert soup.decode() == self.document_for("QUUX<b>bar</b><a>foo</a>BAZ")
  747. # Can't insert an element before itself.
  748. b = soup.b
  749. with pytest.raises(ValueError):
  750. b.insert_before(b)
  751. # Can't insert before if an element has no parent.
  752. b.extract()
  753. with pytest.raises(ValueError):
  754. b.insert_before("nope")
  755. # Can insert an identical element
  756. soup = self.soup("<a>")
  757. soup.a.insert_before(soup.new_tag("a"))
  758. # TODO: OK but what happens?
  759. def test_insert_multiple_before(self):
  760. soup = self.soup("<a>foo</a><b>bar</b>")
  761. soup.b.insert_before("BAZ", " ", "QUUX")
  762. soup.a.insert_before("QUUX", " ", "BAZ")
  763. assert soup.decode() == self.document_for(
  764. "QUUX BAZ<a>foo</a>BAZ QUUX<b>bar</b>"
  765. )
  766. soup.a.insert_before(soup.b, "FOO")
  767. assert soup.decode() == self.document_for(
  768. "QUUX BAZ<b>bar</b>FOO<a>foo</a>BAZ QUUX"
  769. )
  770. def test_insert_after(self):
  771. soup = self.soup("<a>foo</a><b>bar</b>")
  772. soup.b.insert_after("BAZ")
  773. soup.a.insert_after("QUUX")
  774. assert soup.decode() == self.document_for(
  775. "<a>foo</a>QUUX<b>bar</b>BAZ"
  776. )
  777. soup.b.insert_after(soup.a)
  778. assert soup.decode() == self.document_for("QUUX<b>bar</b><a>foo</a>BAZ")
  779. # Can't insert an element after itself.
  780. b = soup.b
  781. with pytest.raises(ValueError):
  782. b.insert_after(b)
  783. # Can't insert after if an element has no parent.
  784. b.extract()
  785. with pytest.raises(ValueError):
  786. b.insert_after("nope")
  787. # Can insert an identical element
  788. soup = self.soup("<a>")
  789. soup.a.insert_before(soup.new_tag("a"))
  790. # TODO: OK but what does it look like?
  791. def test_insert_multiple_after(self):
  792. soup = self.soup("<a>foo</a><b>bar</b>")
  793. soup.b.insert_after("BAZ", " ", "QUUX")
  794. soup.a.insert_after("QUUX", " ", "BAZ")
  795. assert soup.decode() == self.document_for(
  796. "<a>foo</a>QUUX BAZ<b>bar</b>BAZ QUUX"
  797. )
  798. soup.b.insert_after(soup.a, "FOO ")
  799. assert soup.decode() == self.document_for(
  800. "QUUX BAZ<b>bar</b><a>foo</a>FOO BAZ QUUX"
  801. )
  802. def test_insert_after_raises_exception_if_after_has_no_meaning(self):
  803. soup = self.soup("")
  804. tag = soup.new_tag("a")
  805. string = soup.new_string("")
  806. with pytest.raises(ValueError):
  807. string.insert_after(tag)
  808. with pytest.raises(NotImplementedError):
  809. soup.insert_after(tag)
  810. with pytest.raises(ValueError):
  811. tag.insert_after(tag)
  812. def test_insert_before_raises_notimplementederror_if_before_has_no_meaning(self):
  813. soup = self.soup("")
  814. tag = soup.new_tag("a")
  815. string = soup.new_string("")
  816. with pytest.raises(ValueError):
  817. string.insert_before(tag)
  818. with pytest.raises(NotImplementedError):
  819. soup.insert_before(tag)
  820. with pytest.raises(ValueError):
  821. tag.insert_before(tag)
  822. def test_replace_with(self):
  823. soup = self.soup(
  824. "<p>There's <b>no</b> business like <b>show</b> business</p>")
  825. no, show = soup.find_all('b')
  826. show.replace_with(no)
  827. assert soup.decode() == self.document_for(
  828. "<p>There's business like <b>no</b> business</p>"
  829. )
  830. assert show.parent == None
  831. assert no.parent == soup.p
  832. assert no.next_element == "no"
  833. assert no.next_sibling == " business"
  834. def test_replace_with_errors(self):
  835. # Can't replace a tag that's not part of a tree.
  836. a_tag = Tag(name="a")
  837. with pytest.raises(ValueError):
  838. a_tag.replace_with("won't work")
  839. # Can't replace a tag with its parent.
  840. a_tag = self.soup("<a><b></b></a>").a
  841. with pytest.raises(ValueError):
  842. a_tag.b.replace_with(a_tag)
  843. # Or with a list that includes its parent.
  844. with pytest.raises(ValueError):
  845. a_tag.b.replace_with("string1", a_tag, "string2")
  846. def test_replace_with_multiple(self):
  847. data = "<a><b></b><c></c></a>"
  848. soup = self.soup(data)
  849. d_tag = soup.new_tag("d")
  850. d_tag.string = "Text In D Tag"
  851. e_tag = soup.new_tag("e")
  852. f_tag = soup.new_tag("f")
  853. a_string = "Random Text"
  854. soup.c.replace_with(d_tag, e_tag, a_string, f_tag)
  855. assert soup.decode() == "<a><b></b><d>Text In D Tag</d><e></e>Random Text<f></f></a>"
  856. assert soup.b.next_element == d_tag
  857. assert d_tag.string.next_element==e_tag
  858. assert e_tag.next_element.string == a_string
  859. assert e_tag.next_element.next_element == f_tag
  860. def test_replace_first_child(self):
  861. data = "<a><b></b><c></c></a>"
  862. soup = self.soup(data)
  863. soup.b.replace_with(soup.c)
  864. assert "<a><c></c></a>" == soup.decode()
  865. def test_replace_last_child(self):
  866. data = "<a><b></b><c></c></a>"
  867. soup = self.soup(data)
  868. soup.c.replace_with(soup.b)
  869. assert "<a><b></b></a>" == soup.decode()
  870. def test_nested_tag_replace_with(self):
  871. soup = self.soup(
  872. """<a>We<b>reserve<c>the</c><d>right</d></b></a><e>to<f>refuse</f><g>service</g></e>""")
  873. # Replace the entire <b> tag and its contents ("reserve the
  874. # right") with the <f> tag ("refuse").
  875. remove_tag = soup.b
  876. move_tag = soup.f
  877. remove_tag.replace_with(move_tag)
  878. assert soup.decode() == self.document_for(
  879. "<a>We<f>refuse</f></a><e>to<g>service</g></e>"
  880. )
  881. # The <b> tag is now an orphan.
  882. assert remove_tag.parent == None
  883. assert remove_tag.find(string="right").next_element == None
  884. assert remove_tag.previous_element == None
  885. assert remove_tag.next_sibling == None
  886. assert remove_tag.previous_sibling == None
  887. # The <f> tag is now connected to the <a> tag.
  888. assert move_tag.parent == soup.a
  889. assert move_tag.previous_element == "We"
  890. assert move_tag.next_element.next_element == soup.e
  891. assert move_tag.next_sibling == None
  892. # The gap where the <f> tag used to be has been mended, and
  893. # the word "to" is now connected to the <g> tag.
  894. to_text = soup.find(string="to")
  895. g_tag = soup.g
  896. assert to_text.next_element == g_tag
  897. assert to_text.next_sibling == g_tag
  898. assert g_tag.previous_element == to_text
  899. assert g_tag.previous_sibling == to_text
  900. def test_unwrap(self):
  901. tree = self.soup("""
  902. <p>Unneeded <em>formatting</em> is unneeded</p>
  903. """)
  904. tree.em.unwrap()
  905. assert tree.em == None
  906. assert tree.p.text == "Unneeded formatting is unneeded"
  907. def test_wrap(self):
  908. soup = self.soup("I wish I was bold.")
  909. value = soup.string.wrap(soup.new_tag("b"))
  910. assert value.decode() == "<b>I wish I was bold.</b>"
  911. assert soup.decode() == self.document_for("<b>I wish I was bold.</b>")
  912. def test_wrap_extracts_tag_from_elsewhere(self):
  913. soup = self.soup("<b></b>I wish I was bold.")
  914. soup.b.next_sibling.wrap(soup.b)
  915. assert soup.decode() == self.document_for("<b>I wish I was bold.</b>")
  916. def test_wrap_puts_new_contents_at_the_end(self):
  917. soup = self.soup("<b>I like being bold.</b>I wish I was bold.")
  918. soup.b.next_sibling.wrap(soup.b)
  919. assert 2 == len(soup.b.contents)
  920. assert soup.decode() == self.document_for(
  921. "<b>I like being bold.I wish I was bold.</b>"
  922. )
  923. def test_extract(self):
  924. soup = self.soup(
  925. '<html><body>Some content. <div id="nav">Nav crap</div> More content.</body></html>')
  926. assert len(soup.body.contents) == 3
  927. extracted = soup.find(id="nav").extract()
  928. assert soup.decode() == "<html><body>Some content. More content.</body></html>"
  929. assert extracted.decode() == '<div id="nav">Nav crap</div>'
  930. # The extracted tag is now an orphan.
  931. assert len(soup.body.contents) == 2
  932. assert extracted.parent == None
  933. assert extracted.previous_element == None
  934. assert extracted.next_element.next_element == None
  935. # The gap where the extracted tag used to be has been mended.
  936. content_1 = soup.find(string="Some content. ")
  937. content_2 = soup.find(string=" More content.")
  938. assert content_1.next_element == content_2
  939. assert content_1.next_sibling == content_2
  940. assert content_2.previous_element == content_1
  941. assert content_2.previous_sibling == content_1
  942. def test_extract_distinguishes_between_identical_strings(self):
  943. soup = self.soup("<a>foo</a><b>bar</b>")
  944. foo_1 = soup.a.string
  945. bar_1 = soup.b.string
  946. foo_2 = soup.new_string("foo")
  947. bar_2 = soup.new_string("bar")
  948. soup.a.append(foo_2)
  949. soup.b.append(bar_2)
  950. # Now there are two identical strings in the <a> tag, and two
  951. # in the <b> tag. Let's remove the first "foo" and the second
  952. # "bar".
  953. foo_1.extract()
  954. bar_2.extract()
  955. assert foo_2 == soup.a.string
  956. assert bar_2 == soup.b.string
  957. def test_extract_multiples_of_same_tag(self):
  958. soup = self.soup("""
  959. <html>
  960. <head>
  961. <script>foo</script>
  962. </head>
  963. <body>
  964. <script>bar</script>
  965. <a></a>
  966. </body>
  967. <script>baz</script>
  968. </html>""")
  969. [soup.script.extract() for i in soup.find_all("script")]
  970. assert "<body>\n\n<a></a>\n</body>" == str(soup.body)
  971. def test_extract_works_when_element_is_surrounded_by_identical_strings(self):
  972. soup = self.soup(
  973. '<html>\n'
  974. '<body>hi</body>\n'
  975. '</html>')
  976. soup.find('body').extract()
  977. assert None == soup.find('body')
  978. def test_clear(self):
  979. """Tag.clear()"""
  980. soup = self.soup("<p><a>String <em>Italicized</em></a> and another</p>")
  981. # clear using extract()
  982. a = soup.a
  983. soup.p.clear()
  984. assert len(soup.p.contents) == 0
  985. assert hasattr(a, "contents")
  986. # clear using decompose()
  987. em = a.em
  988. a.clear(decompose=True)
  989. assert 0 == len(em.contents)
  990. def test_decompose(self):
  991. # Test PageElement.decompose() and PageElement.decomposed
  992. soup = self.soup("<p><a>String <em>Italicized</em></a></p><p>Another para</p>")
  993. p1, p2 = soup.find_all('p')
  994. a = p1.a
  995. text = p1.em.string
  996. for i in [p1, p2, a, text]:
  997. assert False == i.decomposed
  998. # This sets p1 and everything beneath it to decomposed.
  999. p1.decompose()
  1000. for i in [p1, a, text]:
  1001. assert True == i.decomposed
  1002. # p2 is unaffected.
  1003. assert False == p2.decomposed
  1004. def test_string_set(self):
  1005. """Tag.string = 'string'"""
  1006. soup = self.soup("<a></a> <b><c></c></b>")
  1007. soup.a.string = "foo"
  1008. assert soup.a.contents == ["foo"]
  1009. soup.b.string = "bar"
  1010. assert soup.b.contents == ["bar"]
  1011. def test_string_set_does_not_affect_original_string(self):
  1012. soup = self.soup("<a><b>foo</b><c>bar</c>")
  1013. soup.b.string = soup.c.string
  1014. assert soup.a.encode() == b"<a><b>bar</b><c>bar</c></a>"
  1015. def test_set_string_preserves_class_of_string(self):
  1016. soup = self.soup("<a></a>")
  1017. cdata = CData("foo")
  1018. soup.a.string = cdata
  1019. assert isinstance(soup.a.string, CData)
  1020. class TestDeprecatedArguments(SoupTest):
  1021. def test_find_type_method_string(self):
  1022. soup = self.soup("<a>some</a><b>markup</b>")
  1023. with warnings.catch_warnings(record=True) as w:
  1024. [result] = soup.find_all(text='markup')
  1025. assert result == 'markup'
  1026. assert result.parent.name == 'b'
  1027. msg = str(w[0].message)
  1028. assert msg == "The 'text' argument to find()-type methods is deprecated. Use 'string' instead."
  1029. def test_soupstrainer_constructor_string(self):
  1030. with warnings.catch_warnings(record=True) as w:
  1031. strainer = SoupStrainer(text="text")
  1032. assert strainer.text == 'text'
  1033. msg = str(w[0].message)
  1034. assert msg == "The 'text' argument to the SoupStrainer constructor is deprecated. Use 'string' instead."