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?
參考文章:XPATH簡明指南
XPath中變量用$somevariable
語法即$
符號(hào)加變量名,然后在xpath
方法調(diào)用時(shí)傳參變量值。
>>> # `$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 '
response.xpath('//p[@id={}]'.format(val)).extract_first()
我理解xpath
的參數(shù)也是個(gè)字符串嘛,你試試。
你這個(gè)是python
語句,為什么不用字符串拼接把這個(gè)表達(dá)式拼接起來呢?
比如
response.xpath('//p[@id=' + val + ']').extract_first()