Commits

Yu-Jie Lin committed b707103

Accept and pass namespaces to xpath

  • Participants
  • Parent commits da3b6b3

Comments (0)

Files changed (2)

pyquery/pyquery.py

         else:
             self._parent = no_default
 
+        namespaces = kwargs.get('namespaces', {})
+        if 'namespaces' in kwargs:
+            del kwargs['namespaces']
+
         if kwargs:
             # specific case to get the dom
             if 'filename' in kwargs:
             # select nodes
             if elements and selector is not no_default:
                 xpath = selector_to_xpath(selector)
-                results = [tag.xpath(xpath) for tag in elements]
+                results = [tag.xpath(xpath, namespaces=namespaces) for tag in elements]
                 # Flatten the results
                 elements = []
                 for r in results:
 
         list.__init__(self, elements)
 
-    def __call__(self, *args):
+    def __call__(self, *args, **kwargs):
         """return a new PyQuery instance
         """
         length = len(args)
             return self.__class__([])
         if len(args) == 1 and isinstance(args[0], str) and not args[0].startswith('<'):
             args += (self,)
-        result = self.__class__(*args, **dict(parent=self))
+        result = self.__class__(*args, parent=self, **kwargs)
         return result
 
     # keep original list api prefixed with _
         val = d.__html__()
         assert val == expected, (repr(val), repr(expected))
 
+class TestXMLNamespace(unittest.TestCase):
+    xml = '''<?xml version="1.0" encoding="UTF-8" ?>
+    <foo xmlns:bar="http://example.com/bar">
+    <bar:blah>What</bar:blah>
+    <idiot>123</idiot>
+    </foo>'''
+
+    def test_selector(self):
+        expected = 'What'
+        d = pq(self.xml, parser='xml')
+        val = d('bar|blah', namespaces={'bar': 'http://example.com/bar'}).text()
+        self.assertEqual(repr(val), repr(expected))
+
+    def test_selector_with_xml(self):
+        expected = 'What'
+        d = pq('bar|blah', self.xml, parser='xml', namespaces={'bar': 'http://example.com/bar'})
+        val = d.text()
+        self.assertEqual(repr(val), repr(expected))
+
+    def test_selector_html(self):
+        expected = 'What'
+        d = pq('blah', self.xml, parser='html')
+        val = d.text()
+        self.assertEqual(repr(val), repr(expected))
+
 class TestWebScrapping(unittest.TestCase):
     @with_net
     def test_get(self):