python - how to use variables in xpath
仅有的幸福
仅有的幸福 2017-06-28 09:26:23
0
4
1624

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.

仅有的幸福
仅有的幸福

reply all(4)
洪涛

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 '
typecho
response.xpath('//p[@id={}]'.format(val)).extract_first()

I understand that the parameter of xpath is also a string, please try it.

迷茫

Scrapy Documentation

代言

This is a python statement. Why not use string splicing to splice this expression together?
For example

response.xpath('//p[@id=' + val + ']').extract_first()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!