python - 创建一个 xpath 增加的 for 循环

标签 python python-3.x xpath

我正在尝试创建一个 for 循环,其中 xpath 按钮将被单击 x 次。有一个 xpathes 列表

(//button[@type='button'])[47]
(//button[@type='button'])[65]
(//button[@type='button'])[83]
(//button[@type='button'])[101]
(//button[@type='button'])[119]

所以 xpathes 中的数字增加了 18,这增加到数百万。 我正在尝试创建的程序会询问我单击 xpath 按钮的次数。假设我输入了 5 次。这是我遇到问题的地方。我无法创建一个 for 循环,每次单击 xpath 按钮时数字都会增加 18。我试过了

browser.find_element_by_xpath("(//button[@type='button'])[int(x)]").click()

这样我就可以将 18 加到整数 x 上,但是失败了。任何帮助表示赞赏。 这是代码的样子

print('How many times do you want to click?')
times = input()

x = 47

for i in range(0,int(times), 18):
    browser.find_element_by_xpath("(//button[@type='button'])['str(x)']").click()

更具体地说,

首先我输入 x = 47 然后我输入,

browser.find_element_by_xpath("(//button[@type='button'])[in‌ t(x)]").click()

和语法错误。但是当我输入

browser.find_element_by_xpath("(//button[@type='button'])[47‌ ]").click()

运行正常。我正在尝试使用我分配的变量更改数字“47”。

这是语法错误:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    browser.find_element_by_xpath("(//button[@type='button'])[int(x)]").click()
  File "C:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 293, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element
    'value': value})['value']
  File "C:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "C:\Python35\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression (//button[@type='button'])[int(x)] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '(//button[@type='button'])[int(x)]' is not a valid XPath expression.
  (Session info: chrome=52.0.2743.116)
  (Driver info: chromedriver=2.23.409699 (49blablablablablbalb5129),platform=Windows NT 6.3.9600 x86_64)

最佳答案

您需要使用字符串格式来构造有效的 XPath 查询,例如:

build_xpath = "(//button[@type='button'])[{}]".format
for n in range(47, 47 + 18 * times, 18):
    brower.find_element_by_xpath(build_xpath(n)).click()

关于python - 创建一个 xpath 增加的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39311773/

相关文章:

python - 在卡祖笛中获得选举食谱的现任领导者

python - Keras 数据集的训练集和测试集具有不同的向量长度

javascript - 在 JavaScript 中运行 python

python - Perforce 是否有原生 diff python 函数返回 bool 类型而不是 diff 列表?

Python:如何使用列表检查 csv 列中是否没有值

python-3.x - 如何使用特定的 jar 运行 python Spark 脚本

python - python中有一个包可以创建每月热图吗?

javascript - xpath 在 javascript 中使用命名空间进行评估的问题

java - 在java中使用xpath选择多个节点

html - 最后一个<a>元素的XPath表达式,其“href”属性以数字开头?