XPath中的累加器:可能吗?(Python)

XPath中的累加器:可能吗?(Python),python,selenium,xpath,accumulate,Python,Selenium,Xpath,Accumulate,我正在尝试在XPath中进行累加,可能吗 看看我的代码: driver = webdriver.Chrome() driver.get('http://www.imdb.com/user/ur33778891/watchlist?ref_=wt_nv_wl_all_0') wait = (WebDriverWait, 10) x = 1 while True: try: film = driver.find_element(By.XPATH,

我正在尝试在XPath中进行累加,可能吗

看看我的代码:

driver = webdriver.Chrome()
driver.get('http://www.imdb.com/user/ur33778891/watchlist?ref_=wt_nv_wl_all_0')
wait = (WebDriverWait, 10)
x = 1
while True:

        try:

                film = driver.find_element(By.XPATH, "((//h3[@class='lister-item-header']/a)[%d]"  % x).text
                x = x + 1
                print(film)
问题是,我正试图访问IMDB网站,在用户观察列表中,用这种方法一片一片地获取名称,但正如我看到的那样,无法使用%d来实现此目的,Selenium是否允许使用任何东西来完成这项工作

PS:字符串和数字都不起作用

问题是:如果打开IMDB watchlist,将会有一个电影列表,然后的XPath是相同的//h3[@class='lister-item-header']/a,但我正在考虑如何单独选择,我知道可以这样做:

  //h3[@class='lister-item-header']/a [1] #this will select the first movie
  //h3[@class='lister-item-header']/a [2] #this will select the second movie
film = driver.find_element(By.XPATH, xpath).text

现在,有没有一种方法可以自动做到这一点?我想用累加器,而不是[1],我要把[x]放进去,确定为x=x+1。

使用以下代码:

xpath = "//h3[@class='lister-item-header']/a[{}]".format(x)
在那之后,像这样使用:

  //h3[@class='lister-item-header']/a [1] #this will select the first movie
  //h3[@class='lister-item-header']/a [2] #this will select the second movie
film = driver.find_element(By.XPATH, xpath).text

希望它能帮助你

使用以下代码:

xpath = "//h3[@class='lister-item-header']/a[{}]".format(x)
在那之后,像这样使用:

  //h3[@class='lister-item-header']/a [1] #this will select the first movie
  //h3[@class='lister-item-header']/a [2] #this will select the second movie
film = driver.find_element(By.XPATH, xpath).text
希望它能帮助你

当您从x=1开始时,您可以按如下方式使用索引:

film = driver.find_elements_by_xpath("//h3[@class='lister-item-header']/a")[x].get_attribute("innerHTML")
由于从x=1开始,因此可以按如下方式使用索引:

film = driver.find_elements_by_xpath("//h3[@class='lister-item-header']/a")[x].get_attribute("innerHTML")

“一部一部地给电影命名”有点让人困惑。你能举个例子吗?我编辑过,看看你现在能不能得到。是的,那更好!ta“一片一片地命名”有点让人困惑。你能举个例子吗?我编辑过,看看你现在能不能得到。是的,那更好!太完美了,你最后错过了一个“)”。@LuísHenriqueMartins,我刚刚去掉了所有的括号。谢谢。一切都很顺利,你最后错过了一个“)”字。@LuísHenriqueMartins,我刚刚去掉了所有的括号。谢谢