Selenium Python循环n + 1

时间:2017-04-12 13:17:14

标签: python selenium xpath

while int(driver.find_element_by_css_selector(".quantity").text) < 2:
    driver.find_element_by_css_selector("[id='box-most-popular'] [class='image-wrapper']").click()
    driver.find_element_by_css_selector(".quantity [type='submit']").click()
    n = ???
    wait.until(EC.presence_of_element_located((By.XPATH, "//div[@id='cart']/a[2]/span[.= '%d']" % (n+1))))
    driver.back()

我想增加变量&#34; n&#34;定位器内的每个交互

(By.XPATH, "//div[@id='cart']/a[2]/span[.= '%d']" % (n+1))

但我不知道应该放什么&#34; n&#34;因为它有效, 原始选择器看起来像&#34; //div[@id='cart']/a[2]/span[.= '1']&#34; 在这部分我需要他增加.= '1',如:.= '2'然后.= '3' ......

1 个答案:

答案 0 :(得分:0)

您可以在循环外定义计数器n,然后在每次迭代时将其+1增加:

n = 1
while int(driver.find_element_by_css_selector(".quantity").text) < 2:
    driver.find_element_by_css_selector("[id='box-most-popular'] [class='image-wrapper']").click()
    driver.find_element_by_css_selector(".quantity [type='submit']").click()
    wait.until(EC.presence_of_element_located((By.XPATH, "//div[@id='cart']/a[2]/span[.= '%d']" % n)))
    n += 1
    driver.back()