'Selenium with Python: Using a loop in read text

I am trying to pass the i parameter into the xpath expression, however it seems the syntax is not correct.

i = 1

while i < 9:
   
   day1Temp = driver.find_element(By.XPATH, "//*[@id='wob_dp']/div[", i, "]/div[3]/div[1]/span[1]")
   
print(day1Temp.text)

Can anyone suggest what is wrong here?



Solution 1:[1]

You have initialized

i = 1

Hence i is of type int

Where as within the xpath you need to pass i as a string. So you have to convert the type of i as string.


Solution

Using f-strings your effective code block will be:

i = 1
while i < 9:
   day1Temp = driver.find_element(By.XPATH, f"//*[@id='wob_dp']/div[{str(i)}]/div[3]/div[1]/span[1]")
   
print(day1Temp.text)

Solution 2:[2]

to parse i, you can use f-string like below:

i = 1

while i < 9:
    day1Temp = driver.find_element(By.XPATH, f"//*[@id='wob_dp']/div[{i}]/div[3]/div[1]/span[1]")

Solution 3:[3]

This is how you can fix your code. Also don't forget to increment i

i = 1

while i < 9:   
   day1Temp = driver.find_element(By.XPATH, "//*[@id='wob_dp']/div[%d]/div[3]/div[1]/span[1]" % i)  
   print(day1Temp.text)
   i += 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 cruisepandey
Solution 3 JaSON