如何使用两个变量迭代xpath?

2024-10-01 22:39:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试按如下方式迭代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)

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

Traceback (most recent call last):
File "/Users/marcel/PycharmProjects/AusarbeitungGetter/Ausarbeitung/Ausarbeitung/spiders/Getter.py", line 12, in
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: tuple index out of range

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


Tags: indivformatmainhtmltablesectionrange
1条回答
网友
1楼 · 发布于 2024-10-01 22:39:02

因为您正在访问格式化中的索引1而不是索引0。在括号之间使用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)

相关问题 更多 >

    热门问题