[英]How to click through multiple elements with same XPATH in selenium using for loop?
I'm trying to web scrape different elements with same class name.我正在尝试 web 抓取具有相同 class 名称的不同元素。 The following statements works well.
以下语句运行良好。
browser.find_element(By.XPATH, "(//div[@class= 'jumbo-tracker'])[1]").click()
browser.find_element(By.XPATH, "(//div[@class= 'jumbo-tracker'])[2]").click()
... 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]
看起来,它不识别 (//div[@class= 'jumbo-tracker'])[i]
Here's the code:这是代码:
for i in range(1,length+1):
browser.find_element(By.XPATH, "(//div[@class= 'jumbo-tracker'])[i]").click()
sleep(5)
browser.find_element(By.XPATH, "//div[@class='sc-1y3q50z-3 eiMLBn']").click()
sleep(5)
sno.append(restaurant)
restaurant_name= browser.find_element(By.XPATH,"//h1[contains(@class, 'sc-7kepeu-0 sc-kafWEX kTxZkY')]").text
name.append(restaurant_name)
browser.back()
browser.back()
sleep(5)
Here's the exception:这是例外:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"(//div[@class= 'jumbo-tracker'])[i]"}
Please, help.请帮忙。
You can click all elements keep in for loop and you have to use elements instead of element.您可以单击所有元素保留在 for 循环中,并且必须使用元素而不是元素。
clicks = browser.find_elements(By.XPATH, "//div[@class= 'jumbo-tracker']")
for click in clicks:
click = click.click()
time.sleep(2)
Use string interpolation.使用字符串插值。 String interpolation is a process substituting values of variables into placeholders in a string.
字符串插值是将变量值替换为字符串中的占位符的过程。 This example (based on your code) uses an f-string:
此示例(基于您的代码)使用 f 字符串:
for i in range(1,length+1):
browser.find_element(By.XPATH, f"(//div[@class= 'jumbo-tracker'])[{i}]").click()
The range()
function creates a sequence of numbers. range()
function 创建一个数字序列。
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:因此,在使用f 字符串在xpath中传递变量时,您需要将
number
转换为string
以进行变量替换,您可以使用以下代码行:
for i in range(1,length+1):
browser.find_element(By.XPATH, f"(//div[@class= 'jumbo-tracker'])[{str(i)}]").click()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.