英文:
Selenium - Loop over values for specific find_elements and click
问题
我有一个非常简单但有点棘手的问题。
我正在使用Selenium。
我希望在循环中点击所有元素,逐个点击,其中每个元素由"data-tooltip"属性等于a
的每个值来指定。
for i in a:
tx_click = driver.find_element(By.XPATH, '//a[contains(@data-tooltip, i) and contains(@href, "/transaction/")]').click()
driver.back()
其中a
是:
['5e8d1',
'60e6f',
'3ac8d',
'598f5',
'fab93']
我得到的是它总是只找到第一个元素(即"5e8d1"),并在其上循环。
只有在find_element
内部指定确切的字符串时才有效。
我感激任何帮助!
解决方法:使用f字符串(已编辑接受的评论建议)。
tx_click = driver.find_element(By.XPATH, f'//a[contains(@data-tooltip, "{i}") and contains(@href, "/transaction/")]').click()
英文:
I have a very simple yet tricky question.
I am working with selenium.
I want the following line in the loop to click all elements, one by one,, where each element is specified by the "data-tooltip" attribute being equal to each value of a
.
for i in a:
tx_click = driver.find_element(By.XPATH, '//a[contains(@data-tooltip, i) and contains(@href, "/transaction/")]').click()
driver.back()
where a
is:
['5e8d1',
'60e6f',
'3ac8d',
'598f5',
'fab93']
What I get is that it always finds only the 1st element (i.e., "5e8d1") and loops over it.
It only works if I specify inside the find_element
the exact string.
I appreciate any help!
SOLUTION: Use an f-string (edited suggestion from accepted comment).
tx_click = driver.find_element(By.XPATH, f'//a[contains(@data-tooltip, "{i}") and contains(@href, "/transaction/")]').click()
答案1
得分: 2
你正在比较XPath中硬编码的i
值,而不是从变量中获取的。
将你的代码更新为以下内容,以将变量格式化到XPath中:
for i in a:
tx_click = driver.find_element(By.XPATH, f'//a[contains(@data-tooltip, "{i}") and contains(@href, "/transaction/")]').click()
driver.back()
这应该可以工作。
英文:
You're comparing the hardcoded i
value in the XPath, not from the variable.
Updated your code to this for formatting variable into the XPath:
for i in a:
tx_click = driver.find_element(By.XPATH, f'//a[contains(@data-tooltip, {i}) and contains(@href, "/transaction/")]').click()
driver.back()
This should work.
答案2
得分: 1
你需要使用 find_elements 来获取具有相同标识符的所有元素,并随后将它们放入循环中,逐个点击这些元素。
英文:
You have to get all of elements that has the same identifier in a list by find_elements
after that you can put the elements that you got in for to click them one by one.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论