How To Use Python Variable In An Xpath Expression?
Solution 1:
Use string concatenation in the hosting language so that i
is evaluated before constructing the XPath. Otherwise, [i]
is a predicate testing for the presence of an i
element. You didn't state what your hosting language is, but assuming string concatenation is "string" + "string"
:
"//div[@class='pagedlist_item'][" + i + "]/*/div[@class='ObjectCard-header']/a[@class='user']"
See also: How to pass variable parameter into XPath expression?
Update: Ok, so you're hosting XPath in Python.
You can use +
to concatenate above if you first cast i
to a string via str(i)
,
"//div[@class='pagedlist_item'][" + str(i) + "]/*/div[@class='ObjectCard-header']/a[@class='user']"
or you can use format()
as is used in the link I provided:
"//div[@class='pagedlist_item'][{}]/*/div[@class='ObjectCard-header']/a[@class='user']".format(i)
either way, place the above constructed XPath expressions into your call to find_element_by_xpath()
and your problem should be solved.
Caution: Do not use this approach with untrusted values for i
or you could open your code to XPath injection attacks.
Solution 2:
Firstly cast index/i variable to string using str(index) and then try using below:
content = rows.xpath('//div[@class="LookupHelpDesc"]['+index+']//text()').extract_first()
always use single quote.
Solution 3:
The solution is to first convert the index to a string.
index = str(i)
people = driver.find_element_by_xpath("//div[@class='pagedlist_item'][" + index + "]/*/div[@class='ObjectCard-header']/a[@class='user']")
i++
Post a Comment for "How To Use Python Variable In An Xpath Expression?"