programminglearner
programminglearner

Reputation: 391

How to nest loop number into an xpath in python?

I have the xpath to follow a user on a website in selenium. Here is what I thought of doing so far:

followloop = [1,2,3,4,5,6,7,8,9,10]
for x in followloop:
    driver.find_element_by_xpath("/html/body/div[7]/div/div/div[2]/div[>>>here is where i want the increment to increase<<<]/div[2]/div[1]/div/button").click()

So where I stated in the code is where I want the number to go up in increments. Also as you see with the for loop Im' doing 1,2,3,4,5...can I code it more simply to be like 1-100? Because I don't just want 1-10 I will want it 1-whatever higher number.

I tried to just put x in where I want it but realised that python won't pick up that it's a variable I want to put in that slot and will just consider it as part of the xpath. So how do I make it put the increasing number variable number in there on each loop?

Upvotes: 0

Views: 6145

Answers (3)

SwedishOwlSerpent
SwedishOwlSerpent

Reputation: 355

Use a format string.

And use range() (or xrange() for larger numbers) instead. It does exactly what you want.

for x in range(10):
    driver.find_element_by_xpath("/html/body/div[7]/div/div/div[2]/div[%d]/div[2]/div[1]/div/button" % (x,)).click()

Upvotes: -1

Nika Megutnishvili
Nika Megutnishvili

Reputation: 1

I would use a wildcard '%s' for your task and range() as indicated in previous comments:

for x in range(0,100): 
     driver.find_element_by_xpath("/html/body/div[7]/div/div/div[2]/div[%s]/div[2]/ 
     div[1]/div/button").click() % x

Upvotes: 0

gtlambert
gtlambert

Reputation: 11971

You need to convert the index from the for loop into a string and use it in your xpath:

follow_loop = range(1, 11)
for x in follow_loop:
    xpath = "/html/body/div[7]/div/div/div[2]/div["
    xpath += str(x)
    xpath += "]/div[2]/div[1]/div/button"
    driver.find_element_by_xpath(xpath).click()

Also, there will generally be a neater/better way of selecting an element instead of using the XPath /html/body/div[7]/div/div/div[2]. Try to select an element by class or by id, eg:

//div[@class="a-classname"]
//div[@id="an-id-name"]

Upvotes: 4

Related Questions