How to use variables in xpath. I want to select elements whose id is a certain value. This value is a variable.
response.xpath('//p[@id=val]').extract_first()
The value of val is 'images', what is the syntax for using variables in xpath.
PHP中文网2017-06-28 09:28:23
Reference article: A Concise Guide to XPATH
XPath variables use the $somevariable
syntax, which is the $
symbol plus the variable name, and then the parameter variable value is passed when the xpath
method is called.
>>> # `$val` used in the expression, a `val` argument needs to be passed
>>> response.xpath('//p[@id=$val]/a/text()', val='images').extract_first()
u'Name: My image 1 '
typecho2017-06-28 09:28:23
response.xpath('//p[@id={}]'.format(val)).extract_first()
I understand that the parameter of xpath
is also a string, please try it.
代言2017-06-28 09:28:23
This is a python
statement. Why not use string splicing to splice this expression together?
For example
response.xpath('//p[@id=' + val + ']').extract_first()