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

Accumulators in the XPath: is it possible? (Python)

我正在尝试在 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,但是我在想怎么select然后单独的,我知道可以这样做:

  //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

现在,有没有办法自动执行此操作?我在考虑累加器,而不是 [1] 我要放 [x] 并确定为 x = x + 1.

为此使用以下代码:

xpath = "//h3[@class='lister-item-header']/a[{}]".format(x)

之后像这样使用:

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")