我正在Python中使用Selenium webdriver来查找网页上要处理的元素,如下所示:
driver.find_element_by_xpath('//div[@class="gsc-cursor-page" and text()="1"]')
理想情况下,我想浏览该 div 中的所有文本,text()="1"
、text()="2"
,.. . text()="10"
等。但是由于整个 xpath 是一个字符串,不知何故我找不到一种方法来编写迭代 for i in range(10)
不破坏内部结构。
我能得到的最接近的是
mypath = '//div[@class="gsc-cursor-page" and text()="' + str(i) + '"]'
next = driver.find_element_by_xpath(path)
但这也会导致错误。关于如何解决这个问题有什么建议吗?
最佳答案
这个 XPath,
//div[@class="gsc-cursor-page" and number() >= 1 and number() <= 10]
将选择指定@class
的所有div
元素,其值在1..10
范围内。
用于解决 OP 评论的特定 Python/Selenium 代码
xp = "//div[@class="gsc-cursor-page" and number() >= 1 and number() <= 10]"
for div in driver.find_elements_by_xpath(xp):
div.click()
关于python - 在 XPath 中迭代数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39783329/