创建一个xpath增加的for循环

时间:2016-09-03 22:13:07

标签: 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)

1 个答案:

答案 0 :(得分:1)

您需要使用字符串格式来构造有效的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()