【问题标题】:How can I iterate over a xpath with two variables?如何迭代具有两个变量的 xpath?
【发布时间】:2020-05-26 03:47:02
【问题描述】:

我尝试按如下方式遍历 Xpath:

for i in range (1,9):
     xpath = '/ html / body / div / div / div / main / section / div 
              / div [2] / div / div [1] / div [2] /
              div [1] / table / tbody / tr [1] /td[{1}]'.format(i)

     element = driver.find_element_by_xpath (xpath) .get_attribute ('tabindex')
     print (element)

不幸的是,这似乎不起作用,并导致以下错误消息:

回溯(最近一次通话最后一次):
文件“/Users/marcel/PycharmProjects/AusarbeitungGetter/Ausarbeitung/Au​​sarbeitung/spiders/Getter.py”,第 12 行,在
xpath='/html/body/div/div/div/main/section/div/div[2]/div/div[1]/div[2]/div[1]/table/tbody/tr[1] /td[{1}]'.format(i)
IndexError: 元组索引超出范围

我还想知道我是否可以迭代两个数字,以便我可以为最后一个 td [i] 和最后一个 tr [j] 使用一个变量

【问题讨论】:

    标签: python html selenium xpath


    【解决方案1】:

    因为您在格式中访问的是索引 1 而不是索引 0。在括号之间使用 0 或仅使用括号,因为它将默认为第一个输入。

    xpath = '/ html / body / div / div / div / main / section / div 
              / div [2] / div / div [1] / div [2] /
              div [1] / table / tbody / tr [1] /td[{0}]'.format(i)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2017-08-21
      • 2020-08-08
      • 1970-01-01
      • 2022-10-25
      相关资源
      最近更新 更多