I’m trying to web scrape different elements with same class name. The following statements works well.
JavaScript
x
3
1
browser.find_element(By.XPATH, "(//div[@class= 'jumbo-tracker'])[1]").click()
2
browser.find_element(By.XPATH, "(//div[@class= 'jumbo-tracker'])[2]").click()
3
… and so on.
Now, if I put this in a loop, it doesn’t work. Looks like, it doesn’t recognize (//div[@class= ‘jumbo-tracker’])[i]
Here’s the code:
JavaScript
1
12
12
1
for i in range(1,length+1):
2
browser.find_element(By.XPATH, "(//div[@class= 'jumbo-tracker'])[i]").click()
3
sleep(5)
4
browser.find_element(By.XPATH, "//div[@class='sc-1y3q50z-3 eiMLBn']").click()
5
sleep(5)
6
sno.append(restaurant)
7
restaurant_name= browser.find_element(By.XPATH,"//h1[contains(@class, 'sc-7kepeu-0 sc-kafWEX kTxZkY')]").text
8
name.append(restaurant_name)
9
browser.back()
10
browser.back()
11
sleep(5)
12
Here’s the exception:
JavaScript
1
2
1
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"(//div[@class= 'jumbo-tracker'])[i]"}
2
Please, help.
Advertisement
Answer
range()
The range()
function creates a sequence of numbers.
So while passing the variable within the xpath using f-strings you need to convert the number
as string
for variable substitution and you can use the following line of code:
JavaScript
1
3
1
for i in range(1,length+1):
2
browser.find_element(By.XPATH, f"(//div[@class= 'jumbo-tracker'])[{str(i)}]").click()
3