gpt4 book ai didi

python - 在 XPath 中迭代数字

转载 作者:行者123 更新时间:2023-11-28 01:05:56 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com