2017-03-17 56 views
0

工作代碼是這樣的:如何通過使用Xpath傳遞動態輸入名稱來獲取輸入的值?

csrf = list(set(htmls.xpath("//input[@name='whatever']/@value")))[0] 

不過,我試圖讓輸入名稱作爲傳遞給函數的參數,那樣我會做這樣的事情:

tokenname = sys.argv[2] 

賦予值「什麼」,我想通過它是這樣的:

csrf = list(set(htmls.xpath("//input[@name="+tokenname+"]/@value")))[0] 

但它不工作的方式,反正傳遞變量在@name值?

完整的代碼是在這裏:

import requests 
from lxml import html 
import json 
import sys 

session_requests = requests.session() 
login_url = sys.argv[1] 
tokenname = sys.argv[2] 
result = session_requests.get(login_url) 
htmls = html.fromstring(result.text) 

csrf = list(set(htmls.xpath("//input[@name={}]/@value".format(tokenname))))[0] 

print csrf 

回答

1

編輯

基於討論,看起來就像你有問題,與"和逃生charcaters。 使用以下

csrf = list(set(htmls.xpath("//input[@name=\"{}\"]/@value".format(tokenname))))[0] 


您可以使用format如下

"//input[@name={}]/@value".format('whatever') 

python doc site

str.format(* ARGS,** kwargs)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

>>> "The sum of 1 + 2 is {0}".format(1+2) 
'The sum of 1 + 2 is 3' 
+0

你的意思是這樣的:CSRF =名單(套(htmls.xpath( 「//輸入[@name = {}]/@值」 .format(tokenname))? – user2906838

+0

是的,只需將.format添加到內引號結尾 –

+0

我這樣做:csrf = list(set(htmls.xpath(「// input [@name = {}]/@ value」.format(tokenname))) )[0]仍然不起作用。與之前相同的錯誤 string(35)「IndexError:列表索引超出範圍」 – user2906838

相關問題