gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:24:24 24 4
gpt4 key购买 nike

我正在尝试创建一个 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/

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