简体   繁体   中英

Selenium - How to add integer variable in xpath using python

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM