user2439278
user2439278

Reputation: 1214

How to pass variable inside find_element_by_css_selector method in Selenium , Python

I need to do some changes in below line :

driver.find_element_by_css_selector("p[title=\"sanityapp5\"]").click()

Now I have create a string variable appname

appname="sanityapp5"

Now I want to know how to replace sanityapp5 with variable appname in above selenium command. I am new to python so do know how to do this.

Upvotes: 0

Views: 3186

Answers (2)

B.Mr.W.
B.Mr.W.

Reputation: 19628

Let's do it in a more Pythonic way. Use format function.

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "hello world{}".format("end")
'hello worldend'
>>> "hello world {1} and {0}".format("a", "b")
'hello world b and a'
>>> 

And it is in your case

driver.find_element_by_css_selector("p[title=\"{0}\"]".format(appname)).click()
>>> appname="sanityapp5"
>>> "p[title=\"{0}\"]".format(appname)
'p[title="sanityapp5"]'

Few reasons why you prefer format to percentage.

Upvotes: 1

wRAR
wRAR

Reputation: 25693

driver.find_element_by_css_selector("p[title=\"%s\"]" % appname).click()

or using the newer style string formatting:

driver.find_element_by_css_selector("p[title=\{}\"]".format(appname)).click()

Upvotes: 1

Related Questions