简体   繁体   English

Selenium-如何使用python在xpath中添加整数变量

[英]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. 我是selenium / python的新手,这是我的问题:我有一个简单的网站,提供了一些新闻。 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: 我尝试编写遍历所有新闻的脚本,打开每个新闻,执行某些操作,然后返回所有其他新闻。所有新闻都具有相同的xpath,仅与最后一个符号有所不同-我尝试将此符号作为变量并遍历所有新闻,每次访问新闻后增加我的变量:

     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 Python返回错误:“除了类型“ str”,取而代之的是“ int”。Google几个小时了,但实际上无法处理它。非常感谢您的帮助

You are trying to add a string and a int which is is why the exception. 您试图添加一个字符串和一个int,这就是为什么例外。 Use str(i) instead of i 使用str(i)代替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). 在上面的{0}中用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. 您可以使用.format通过将它们提供为位置值来替换字符串中的多个变量,使用+连接字符串更容易使用。

refer: http://thepythonguru.com/python-string-formatting/ 请参阅: http : //thepythonguru.com/python-string-formatting/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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