Tarik Zorlar Tarik Zorlar - 1 year ago 71
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


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


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

To be more specific,

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


and syntax error. but when i type in


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>
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
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 Source

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