From a36e7ac2a24bf8aa91b51da3c82ad11368adb146 Mon Sep 17 00:00:00 2001 From: Leonard Richardson Date: Mon, 24 Dec 2018 09:54:10 -0500 Subject: Keep track of the namespace abbreviations found while parsing the document. This makes select() work most of the time without requiring a value for 'namespaces'. --- doc/source/index.rst | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) (limited to 'doc') diff --git a/doc/source/index.rst b/doc/source/index.rst index 2977029..9bf9cf1 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -1781,8 +1781,7 @@ first tag that matches a selector:: # Elsie If you've parsed XML that defines namespaces, you can use them in CSS -selectors. You just have to pass a dictionary of the namespace -mappings into ``select()``:: +selectors.:: from bs4 import BeautifulSoup xml = """ @@ -1794,15 +1793,23 @@ mappings into ``select()``:: soup.select("child") # [I'm in namespace 1, I'm in namespace 2] - namespaces = dict(ns1="http://namespace1/", ns2="http://namespace2/") soup.select("ns1|child", namespaces=namespaces) # [I'm in namespace 1] -All of this is a convenience for people who know the CSS selector -syntax. You can do all this stuff with the Beautiful Soup API. And if -CSS selectors are all you need, you should parse the document -with lxml: it's a lot faster. But this lets you `combine` CSS -selectors with the Beautiful Soup API. +When handling a CSS selector that uses namespaces, Beautiful Soup +uses the namespace abbreviations it found when parsing the +document. You can override this by passing in your own dictionary of +abbreviations:: + + namespaces = dict(first="http://namespace1/", second="http://namespace2/") + soup.select("second|child", namespaces=namespaces) + # [I'm in namespace 2] + +All this CSS selector stuff is a convenience for people who already +know the CSS selector syntax. You can do all of this with the +Beautiful Soup API. And if CSS selectors are all you need, you should +parse the document with lxml: it's a lot faster. But this lets you +`combine` CSS selectors with the Beautiful Soup API. Modifying the tree ================== -- cgit v1.2.1