Heim  >  Fragen und Antworten  >  Hauptteil

Python – wie man Variablen in XPath verwendet

Wie verwende ich Variablen in XPath? Ich möchte Elemente auswählen, deren ID einen bestimmten Wert hat. Dieser Wert ist eine Variable.

response.xpath('//p[@id=val]').extract_first()

Wobei der Wert von val „images“ ist, wie lautet die Syntax für die Verwendung von Variablen in XPath?

仅有的幸福仅有的幸福2669 Tage vor1630

Antworte allen(4)Ich werde antworten

  • PHP中文网

    PHP中文网2017-06-28 09:28:23

    参考文章:XPATH简明指南

    XPath中变量用$somevariable语法即$符号加变量名,然后在xpath方法调用时传参变量值。

    >>> # `$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 '

    Antwort
    0
  • typecho

    typecho2017-06-28 09:28:23

    response.xpath('//p[@id={}]'.format(val)).extract_first()

    我理解xpath的参数也是个字符串嘛,你试试。

    Antwort
    0
  • 迷茫

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

    Scrapy文档

    Antwort
    0
  • 代言

    代言2017-06-28 09:28:23

    你这个是python语句,为什么不用字符串拼接把这个表达式拼接起来呢?
    比如

    response.xpath('//p[@id=' + val + ']').extract_first()

    Antwort
    0
  • StornierenAntwort