search

Home  >  Q&A  >  body text

python - how to use variables in xpath

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.

仅有的幸福仅有的幸福2699 days ago1661

reply all(4)I'll reply

  • PHP中文网

    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 '

    reply
    0
  • typecho

    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.

    reply
    0
  • 迷茫

    迷茫2017-06-28 09:28:23

    Scrapy Documentation

    reply
    0
  • 代言

    代言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()

    reply
    0
  • Cancelreply