How to convert variable to xpath python

from lxml import html
import requests

pagina = 'http://www.beleggen.nl/amx'
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

      

+3


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)

      

+6


source


Nearly...



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

      

+2


source


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)
print(aandeel)

      

See the lmxl docs for more information: http://lxml.de/xpathxslt.html#the-xpath-method

+1


source







All Articles