Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

DOC Mention XPath variables in Selectors section

Paul Tremberth1c0b8053579e
diff --git a/docs/topics/selectors.rst b/docs/topics/selectors.rst
index 39ec9b73c..43370d479 100644
--- a/docs/topics/selectors.rst
+++ b/docs/topics/selectors.rst
@@ -283,6 +283,40 @@ XPath specification.
.. _Location Paths: https://www.w3.org/TR/xpath#location-paths
+.. _topics-selectors-xpath-variables:
+
+Variables in XPath expressions
+------------------------------
+
+XPath allows you to reference variables in your XPath expressions, using
+the ``$somevariable`` syntax. This is somewhat similar to parameterized
+queries or prepared statements in the SQL world where you replace
+some arguments in your queries with placeholders like ``?``,
+which are then substituted with values passed with the query.
+
+Here's an example to match an element based on its "id" attribute value,
+without hard-coding it (that was shown previously)::
+
+ >>> # `$val` used in the expression, a `val` argument needs to be passed
+ >>> response.xpath('//div[@id=$val]/a/text()', val='images').extract_first()
+ u'Name: My image 1 '
+
+Here's another example, to find the "id" attribute of a ``<div>`` tag containing
+five ``<a>`` children (here we pass the value ``5`` as an integer)::
+
+ >>> response.xpath('//div[count(a)=$cnt]/@id', cnt=5).extract_first()
+ u'images'
+
+All variable references must have a binding value when calling ``.xpath()``
+(otherwise you'll get a ``ValueError: XPath error:`` exception).
+This is done by passing as many named arguments as necessary.
+
+`parsel`_, the library powering Scrapy selectors, has more details and examples
+on `XPath variables`_.
+
+.. _parsel: https://parsel.readthedocs.io/
+.. _XPath variables: https://parsel.readthedocs.io/en/latest/usage.html#variables-in-xpath-expressions
+
Using EXSLT extensions
----------------------