如何在xpath python中转换变量

时间:2014-10-10 10:34:12

标签: python python-2.7 xpath lxml python-requests

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

这部分有效,但我想阅读不同标题的多行,是否可以将“Imtech”部分更改为变量?

像这样的东西,它显然不起作用,但我哪里出错了?或者这不容易吗?

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

3 个答案:

答案 0 :(得分:8)

你几乎是对的:

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

答案 1 :(得分:3)

...几乎

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

答案 2 :(得分:3)

XPath允许$variables和lxml的.xpath()方法允许将这些变量的值作为关键字参数提供:.xpath('$variable', variable='my value')

使用您的示例,您可以按照以下方式进行操作:

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

有关详细信息,请参阅lmxl的文档:http://lxml.de/xpathxslt.html#the-xpath-method