2015-07-03 56 views
1

我也需要一些替換文本的XPath的工作:如何在xpath查詢中使用變量?

response.xpath("//h2[@class='brownBackground']/a[@href='/friend/user/4074594-kiki']/text()") 

然而,這href='/friend/user/4074594-kiki'值需要返回基於URL:

x='/friend/user/'+''.join(re.findall(r'https://www.goodreads.com/user/show/(.*)','https://www.goodreads.com/user/show/4074594-kiki')) 

當我使用:

response.xpath("//h2[@class='brownBackground']/a[@href=x]/text()") 

它停止工作。我懷疑這是因爲引號""使路徑字符串文字,因此x不再返回x值,但"x"

回答

2

Python不會奇蹟般地開始用正好在範圍內的變量的內容替換字符串中的字符 - 那將是瘋狂地令人沮喪!如果你想要把x成字符串,是明確

response.xpath(
    "//h2[@class='brownBackground']/a[@href={!r}]/text()".format(x) 
) 

參見str.format的文檔。

+0

非常感謝!奇蹟般有效。 – kevin

+0

@laomao http://stackoverflow.com/help/someone-answers – jonrsharpe