0

Im new with selenium/python and that my problem: I have a simple site with a couple of news. I try to write script that iterates over all news, open each one, do something and goes back to all other news All news have same xpath, difference only with last symbol - i try to put this symbol as variable and loop over all news, with increment my variable after every visited news:

     x = len(driver.find_elements_by_class_name('cards-news-event'))
            print (x)
            for i in range(x):
     driver.find_element_by_xpath('/html/body/div[1]/div[1]/div/div/div/div[2]/div/div[3]/div/div[1]/div/**a["'+i+'"]**').click()
     do something                
      i = i+1

Python return error: "Except type "str", got "int" instead. Google it couple of hours but really can't deal with it Very appreciate for any help

2
  • 4
    Did you try a["'+str(i)+'"] or '.../a["%s"]' % i? P.S. Do not use absolute XPath expressions Commented Jan 24, 2018 at 16:07
  • There's also '.../a["{}"]'.format(i) with python3 and f'.../a["{i}"]' starting with python3.6. Commented Jan 24, 2018 at 16:39

1 Answer 1

1

You are trying to add a string and a int which is is why the exception. Use str(i) instead of i

xpath_string = '/html/body/div[1]/div[1]/div/div/div/div[2]/div/div[3]/div/div[1]/div/**a[{0}]**'.format(str(i))    
driver.find_element_by_xpath(xpath_string).click()

In the above the {0} is replaced with str(i). You can use .format to substitute multiple variables in a string by providing them as positional values, it is more elegant and easy to use that using + to concatenate strings.

refer: http://thepythonguru.com/python-string-formatting/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.