From cb8353294f2c0c0cd3bedacf36ecdf7bc710c979 Mon Sep 17 00:00:00 2001 From: Leonard Richardson Date: Sun, 15 Jul 2018 20:04:03 -0400 Subject: You can pass a dictionary of into BeautifulSoup.new_tag. This makes it possible to create a tag with an attribute like 'name' that would otherwise be masked by another argument of new_tag. [bug=1779276] --- NEWS.txt | 5 +++++ bs4/__init__.py | 5 +++-- bs4/tests/test_tree.py | 6 +++--- test-all-versions | 0 4 files changed, 11 insertions(+), 5 deletions(-) mode change 100644 => 100755 test-all-versions diff --git a/NEWS.txt b/NEWS.txt index 45a6952..52edd4c 100644 --- a/NEWS.txt +++ b/NEWS.txt @@ -21,6 +21,11 @@ bs4.element.Formatter and passing a Formatter instance into (e.g.) encode(). [bug=1716272] +* You can pass a dictionary of `attrs` into + BeautifulSoup.new_tag. This makes it possible to create a tag with + an attribute like 'name' that would otherwise be masked by another + argument of new_tag. [bug=1779276] + = 4.6.0 (20170507) = * Added the `Tag.get_attribute_list` method, which acts like `Tag.get` for diff --git a/bs4/__init__.py b/bs4/__init__.py index 329ef53..409f528 100644 --- a/bs4/__init__.py +++ b/bs4/__init__.py @@ -356,9 +356,10 @@ class BeautifulSoup(Tag): self.preserve_whitespace_tag_stack = [] self.pushTag(self) - def new_tag(self, name, namespace=None, nsprefix=None, **attrs): + def new_tag(self, name, namespace=None, nsprefix=None, attrs={}, **kwattrs): """Create a new tag associated with this soup.""" - return Tag(None, self.builder, name, namespace, nsprefix, attrs) + kwattrs.update(attrs) + return Tag(None, self.builder, name, namespace, nsprefix, kwattrs) def new_string(self, s, subclass=NavigableString): """Create a new NavigableString associated with this soup.""" diff --git a/bs4/tests/test_tree.py b/bs4/tests/test_tree.py index e8903e3..e5cc47e 100644 --- a/bs4/tests/test_tree.py +++ b/bs4/tests/test_tree.py @@ -703,12 +703,12 @@ class TestTagCreation(SoupTest): """Test the ability to create new tags.""" def test_new_tag(self): soup = self.soup("") - new_tag = soup.new_tag("foo", bar="baz") + new_tag = soup.new_tag("foo", bar="baz", attrs={"name": "a name"}) self.assertTrue(isinstance(new_tag, Tag)) self.assertEqual("foo", new_tag.name) - self.assertEqual(dict(bar="baz"), new_tag.attrs) + self.assertEqual(dict(bar="baz", name="a name"), new_tag.attrs) self.assertEqual(None, new_tag.parent) - + def test_tag_inherits_self_closing_rules_from_builder(self): if XML_BUILDER_PRESENT: xml_soup = BeautifulSoup("", "lxml-xml") diff --git a/test-all-versions b/test-all-versions old mode 100644 new mode 100755 -- cgit v1.2.1