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
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 to share