Search code examples
pythonpython-2.7xpathstring-formattingstring-concatenation

String concatenation with python and xpath


Instead of writing 10+ IF statements, I'm trying to create one IF statement using a variable. Unfortunately, I'm not familiar with how to implement string concatenation for xpath using python. Can anyone teach me how to perform string formatting for the following code segments?

I would greatly appreciate it, thanks.

   if page_number == 1:
        next_link = browser.find_element_by_xpath('//*[@title="Go to page 2"]')
        next_link.click()

        page_number = page_number + 1
        time.sleep(30)

   elif page_number == 2:
        next_link = browser.find_element_by_xpath('//*[@title="Go to page 3"]')
        next_link.click()

        page_number = page_number + 1
        time.sleep(30)

Solution

  • You can use a for-loop

    Ex:

    for i in range(1, 10):
        next_link = browser.find_element_by_xpath('//*[@title="Go to page {0}"]'.format(str(i+1)))     #using str.format for page number
        next_link.click()
        time.sleep(30)