Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use a variable in selenium webdriver find element by xpath?

so I have a variable named folder which contains a string that I randomly generate. I want to use xpath to find this folder by name, and I am not sure how to put this into action

driver.find_element_by_xpath('//div[text()="variable"]')

where variable contains the randomized text. With sql it would be like this (select * from table where value =(?)), [variable] ...or something similar

like image 204
gallly Avatar asked Jun 20 '13 20:06

gallly


People also ask

Can we use variable in xpath in Selenium?

XPath is a strong tool in itself, but you can even use variables in your XPath expressions. The way it works is by referring to a variable as: $variable. You use the variable element to assign a value to a variable. Variables are case sensitive, so e.g. $var is not the same as $Var.

How do I use Xpath to find elements?

We can find an element using the xpath locator with Selenium webdriver. To identify the element with xpath, the expression should be //tagname[@attribute='value']. To identify the element with xpath, the expression should be //tagname[@class='value']. There can be two types of xpath – relative and absolute.

How does xpath find elements in Selenium?

Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.

How do I find an element that contains specific text in Selenium Webdriver?

We can find an element that contains specific text with Selenium webdriver in Python using the xpath. This locator has functions that help to verify a specific text contained within an element. The function text() in xpath is used to locate a webelement depending on the text visible on the page.


1 Answers

Try this:

driver.find_element_by_xpath('//div[text()="%s"]' % variable)
like image 149
alecxe Avatar answered Nov 15 '22 00:11

alecxe