Tarik Zorlar Tarik Zorlar - 3 months ago 25
Python Question

creating a for loop where xpath increases

I am trying to create a for loop where xpath buttons are to be clicked for x times. There is a list of xpathes

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


So the numbers in xpathes increases by 18 and this goes up to millions.
The Program i'm trying to create will ask me how many times to click the xpath buttons. Let's say i input 5 times. Here's where i have my problem. I can't make a for loop where the number increases by 18 everytime it clicks an xpath button. I tried

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


so that i can add 18 to integer x, but failed. Any help is appreciated.
Here is what the code will look like

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()


To be more specific,

first i type in x = 47 then i type in,

browser.find_element_by_xpath("(//button[@type='button'])[inβ€Œβ€‹t(x)]").click()


and syntax error. but when i type in

browser.find_element_by_xpath("(//button[@type='button'])[47β€Œβ€‹]").click()


it runs normally. I'm trying to change the number '47' with a variable i assigned.

Here is the Syntax error:

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)

Answer

You need to use string formatting to construct a valid XPath query, eg:

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