How to convert variable to xpath python

from lxml import html
import requests

pagina = ''
page = requests.get(pagina)
tree = html.fromstring(page.text)

aandeel = tree.xpath('//a[@title="Imtech"]/text()')
print aandeel


This part works, but I want to read multiple lines with different headers, is it possible to change the "Imtech" part to a variable?

Something like this obviously doesn't work, but where did I go wrong? Or is it not quite that simple?

FondsName = "Imtech"
aandeel = tree.xpath('//a[@title="%s"]/text()')%(FondsName)
print aandeel



source to share

3 answers

You were almost right:

variabelen = [var1,var2,var3]
for var in variabelen:
    aandeel = tree.xpath('//a[@title="%s"]/text()' % var)





FondsName = "Imtech"
aandeel = tree.xpath('//a[@title="%s"]/text()'%FondsName)
print aandeel




XPath allows you to use method $variables

and lxml .xpath()

to provide values ​​for these variables as keyword arguments:.xpath('$variable', variable='my value')

Using your example, this is how you would do it:

fonds_name = 'Imtech'
aandeel = tree.xpath('//a[@title="$title"]/text()', title=fonds_name)


See the lmxl docs for more information:



All Articles